04-线程同步
同步方法
class Account {
private Integer total;
public Account(int total) {
this.total = total;
}
public synchronized void draw(int money) {
if (total >= money) {
this.total = this.total - money;
System.out.println(Thread.currentThread().getName() + "剩下" + this.total);
} else {
System.out.println(Thread.currentThread().getName() + "不够了");
}
}
public synchronized int getTotal() {
return total;
}
}
public class Demo_02_04_1_ThreadSync {
public static void main(String[] args) {
Account account = new Account(100);
Runnable runnable = new Runnable() {
@Override
public void run() {
while (account.getTotal() >= 10) {
account.draw(10);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread A = new Thread(runnable);
A.setName("A");
Thread B = new Thread(runnable);
B.setName("B");
A.start();
B.start();
}
}同步代码块
锁
最后更新于