唐僧喜欢小龙女

导航

多个线程操作一个变量(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



 

posted on 2021-05-16 14:46  与时具进&不忘初心  阅读(287)  评论(0编辑  收藏  举报