java:多线程 wait notify 线程间的通信

1、多个线程0和1之间的交替

java:多线程 wait notify 线程间的通信





public class ClientThread4 {


public static void main(String[] args) {
OpreateNum onum=new OpreateNum();
Thread t1=new ThreadAdd(onum);
Thread t2=new ThreadDel(onum);
Thread t3=new ThreadAdd(onum);
Thread t4=new ThreadDel(onum);
t1.start();
t2.start();
t3.start();
t4.start();
}


}


class OpreateNum{

private int num;
public synchronized void add(){
while(num!=0){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num++;
System.out.println(num);
notify();
}
public synchronized void del(){
while(num==0){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num--;
System.out.println(num);
notify();
}


}


class ThreadAdd extends Thread{
private OpreateNum obj;
public ThreadAdd(OpreateNum obj){
this.obj=obj;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.obj.add();
}

}
}


class ThreadDel extends Thread{
private OpreateNum obj;
public ThreadDel(OpreateNum obj){
this.obj=obj;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.obj.del();
}
}
}