public class TestSynchronized {
int money = 0;
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
void updateMoney(int number) { // 临界代码块
synchronized (this) {
System.out.println(Thread.currentThread().getName() + "已经进入同步代码块");
int money = getMoney();// 临界的资源
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
money += number;
setMoney(money);
System.out.println(Thread.currentThread().getName()
+ "即将退出updateMoney");
}
}
Object lock = new Object();
class SaveMoneyThread1 extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName()
+ "尝试updateMoney");
updateMoney(200);
}
}
class SaveMoneyThread2 extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName()
+ "尝试updateMoney");
updateMoney(800);
}
}
void test() throws Exception {
Thread thread1 = new SaveMoneyThread1();
Thread thread2 = new SaveMoneyThread2();
thread1.start();
thread2.start();
try {
Thread.sleep(5000);
} catch (Exception e) {
}
;
System.out.println(money);
}
public static void main(String[] args) throws Exception {
new TestSynchronized().test();
}
}
===================================
打印会有两种结果:
Thread-0尝试updateMoney
Thread-1尝试updateMoney
Thread-1已经进入同步代码块
Thread-1即将退出updateMoney
Thread-0已经进入同步代码块
Thread-0即将退出updateMoney
1000
--------------------------------------------------------------
Thread-0尝试updateMoney
Thread-1尝试updateMoney
Thread-0已经进入同步代码块
Thread-0即将退出updateMoney
Thread-1已经进入同步代码块
Thread-1即将退出updateMoney
1000
两种结果正好说明方法同步的效果