多个线程操作一个变量(synchronized)

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



 

上一篇:二分图全解


下一篇:JUC学习-2