線程虛假喚醒

多線程中不允許用if做判斷,只能用while去循環(loop)

線程虛假喚醒

多線程出現number加減出現2原因解析,使用while就不會出現這種情況
在這裏插入圖片描述

package juc;

class NumberUpAndDown{
    private int number = 0;
    public synchronized void numberUp() throws InterruptedException{
        while (number != 0)
        {
            this.wait();
        }
        ++number;
        System.out.println("線程名字"+Thread.currentThread().getName()+"number="+number);
        this.notifyAll();
    }
    public synchronized void numberDown() throws InterruptedException{
        while (number == 0)
        {
            this.wait();
        }
        --number;
        System.out.println("線程名字"+Thread.currentThread().getName()+"number="+number);
        this.notifyAll();
    }
}

public class WaitNotifyDemo {
    public static void main(String[] args){

        NumberUpAndDown numberUpAndDown = new NumberUpAndDown();

        new Thread(()->{
            for (int i = 1; i <= 10 ; i++){
                try {
                    Thread.sleep(200);
                    numberUpAndDown.numberUp();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"AA").start();

        new Thread(()->{
            for(int i = 1; i <= 10 ; i++){
                try{
                    Thread.sleep(300);
                    numberUpAndDown.numberDown();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }, "BB").start();

        new Thread(()->{
            for (int i = 1; i <= 10 ; i++){
                try {
                    Thread.sleep(400);
                    numberUpAndDown.numberUp();
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"CC").start();

        new Thread(()->{
            for(int i = 1; i <= 10 ; i++){
                try{
                    Thread.sleep(400);
                    numberUpAndDown.numberDown();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }, "DD").start();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章