public class WindowSell2 { private int num=0; public synchronized void increade() throws InterruptedException{ while (num != 0){ this.wait(); } num++; System.out.println("当前线程是"+Thread.currentThread().getName()+"num="+num); this.notifyAll(); } public synchronized void decreade() throws InterruptedException{ while (num == 0){ this.wait(); } num--; System.out.println("当前线程是"+Thread.currentThread().getName()+"num="+num); this.notifyAll(); } }
public class MainTest {
public static void main(String[] args) {
/**
*
* 两个线程进行操作
*
*
*
*
*/
WindowSell2 windowSell2 = new WindowSell2();
new Thread(()->{
try {
for (int i = 0; i < 12; i++) {
windowSell2.increade();
}
}catch (InterruptedException e){
}
},"A").start();
new Thread(()->{
try {
for (int i = 0; i < 12; i++) {
windowSell2.decreade();
}
}catch (InterruptedException e){
}
},"B").start();
new Thread(()->{
try {
for (int i = 0; i < 12; i++) {
windowSell2.decreade();
}
}catch (InterruptedException e){
}
},"C").start();
}
}
当前线程是Anum=1
当前线程是Bnum=0
当前线程是Anum=1
当前线程是Bnum=0
当前线程是Anum=1
当前线程是Bnum=0
当前线程是Anum=1
当前线程是Bnum=0
当前线程是Anum=1
当前线程是Cnum=0
当前线程是Anum=1
当前线程是Bnum=0
当前线程是Anum=1
当前线程是Cnum=0
当前线程是Anum=1