多線程案例分析一:數(shù)字加減

??設(shè)計4個線程對象,2個線程執(zhí)行減操作,2個線程執(zhí)行加操作。

public class ThreadDemo {
    public static void main(String[] args) throws Exception {
        Resource res = new Resource();
        SubThread st = new SubThread(res);
        AddThread at = new AddThread(res);
        new Thread(at, "A ").start();
        new Thread(at, "B ").start();
        new Thread(st, "X ").start();
        new Thread(st, "Y ").start();
    }
}
class AddThread implements Runnable {
    private Resource resource;
    public AddThread(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                this.resource.add();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class SubThread implements Runnable {
    private Resource resource;
    public SubThread(Resource resource) {
        this.resource = resource;
    }
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                this.resource.sub();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Resource {//定義一個操作的資源
    private int num = 0;//這個是要進行加減操作的數(shù)據(jù)
    private boolean flag = true;//加減的切換
    //flag = true:表示可以進行加法操作,但是無法進行減法操作
    //flag = false:表示可以進行減法操作,但是無法進行加法操作
    public synchronized void add() throws InterruptedException {//執(zhí)行加法操作
        while (flag == false) {//現(xiàn)在需要執(zhí)行的是減法操作,加法操作要等待
            System.out.println("【加法操作 -" + Thread.currentThread().getName() + "】進行等待");
            super.wait();
            System.out.println("【加法操作 -" + Thread.currentThread().getName() + "】被釋放");
        }
        Thread.sleep(100);
        this.num++;
        System.out.println("【加法操作 -" + Thread.currentThread().getName() + "】num = " + this.num);
        this.flag = false;//加法操作執(zhí)行完畢,需要執(zhí)行減法操作
        super.notifyAll();//喚醒全部等待線程

    }
    public synchronized void sub() throws InterruptedException {//執(zhí)行減法操作
        while (flag == true) { //減法操作需要等待,注意:一定要用while 詳見:https://www.cnblogs.com/LeeScofiled/p/7225562.html
            System.out.println("【減法操作 -" + Thread.currentThread().getName() + "】進行等待");
            super.wait();
        }
        Thread.sleep(200);
        this.num--;
        System.out.println("【減法操作 -" + Thread.currentThread().getName() + "】num = " + this.num);
        this.flag = true;
        super.notifyAll();
    }
}

??這是一個經(jīng)典的多線程開發(fā)操作,這個程序中一定要考慮的核心本質(zhì)在于:加一個、減一個,整體的計算結(jié)果應該在0、1(或-1) 中循環(huán)出現(xiàn)才是合理的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容