文章目录
线程通信
public class FatherMoney {
public static void main(String[] args) {
SuperAccount account = new SuperAccount();
new GetThread("小张",account).start();
new GetThread("小王",account).start();
new SaveThread("老王",account).start();
new SaveThread("老张",account).start();
new SaveThread("老刘",account).start();
}
}
@Setter
@Getter
class SuperAccount{
private Integer money=0;
public synchronized void save(Integer money)throws Exception{
if (this.money==0){
this.money = money;
System.out.println(Thread.currentThread().getName()+"存了"+money);
notifyAll();
wait();
}else {
notifyAll();
wait();
}
}
public synchronized void get(Integer money)throws Exception{
if(this.money!=0){
System.out.println(Thread.currentThread().getName()+"取了"+money);
this.money=0;
notifyAll();
wait();
}else {
notifyAll();
wait();
}
}
}
class GetThread extends Thread{
private SuperAccount superAccount;
public GetThread(String name, SuperAccount superAccount) {
super(name);
this.superAccount = superAccount;
}
@Override
public void run(){
while (true){
try {
superAccount.get(10000);
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class SaveThread extends Thread{
private SuperAccount superAccount;
public SaveThread(String name, SuperAccount superAccount) {
super(name);
this.superAccount = superAccount;
}
@Override
public void run(){
while (true){
try {
superAccount.save(10000);
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}