線程交互

線程交互java

例子:如今須要計算1+2+3+...+100,其中A線程負責計算,B線程負責展現計算結果。這樣的話B線程必須等到A線程計算完結果後後才能執行,A也要將本身計算完狀態通知B,因此A、B須要交互。
ide

//B線程負責展現計算結果
public class ThreadB {
    public static void main(String[] args) {
        ThreadA a = new ThreadA();
        a.start();
        synchronized (a){
            System.out.println("等待對象b完成計算~~~");
            try {
                b.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("b對象計算的總和是:" + a.total);
        }
    }
}
//A線程負責計算
public class ThreadA extends Thread {
    int total;

    @Override
    public void run() {
        synchronized (this) {
            for (int i = 1; i <= 100; i++) {
                total += i;
            }
        }
        notify();
    }
}

//計算結果
等待對象b完成計算。。。
b對象計算的總和是:5050

上面的例子是A線程計算,B線程獲取結果,若是如今是C、D也要獲取結果該如何處理,其實很簡單將notify()改成notifyAll();this

例子以下:spa

//計算器
public class Calculator extends Thread {
    int total;

    @Override
    public void run() {
        synchronized (this){
            for(int i = 0; i < 101; i++){
                total += i;
            }
            //注意notifyAll()必須是在synchronized中,要否則會報錯,具體下篇分析
            notifyAll();
        }

    }
}
//獲取計算結果
public class ReaderResult extends Thread {
    Calculator c;

    public ReaderResult(Calculator c) {
        this.c = c;
    }

    @Override
    public void run() {
        synchronized (c) {
            try {
                System.out.println(Thread.currentThread() + "等待計算結...");
                        c.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread() + "計算結果爲:" + c.total);
        }
    }


    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        //啓動三個線程,獲取計算結果
        new ReaderResult(calculator).start();
        new ReaderResult(calculator).start();
        new ReaderResult(calculator).start();
        //啓動計算線程
        calculator.start();
    }

}
//執行結果
Thread[Thread-1,5,main]等待計算結...
Thread[Thread-3,5,main]等待計算結...
Thread[Thread-2,5,main]等待計算結...
Thread[Thread-2,5,main]計算結果爲:5050
Thread[Thread-3,5,main]計算結果爲:5050
Thread[Thread-1,5,main]計算結果爲:5050

此處用到了synchronized關鍵字,下篇介紹線程同步時,具體介紹synchronized。線程

相關文章
相關標籤/搜索