1.2 多線程join的簡單使用示例

join的簡單使用示例,通過構造函數,把b線程放到a線程之後,然後在a線程中使用b.join,實現簡單的線程順序完成

public class UseJoin {
    public static void main(String[] args) {
        WaitB b = new WaitB();
        WaitA a = new WaitA(b);
        a.start();
        b.start();
    }
}

class WaitA extends Thread {
    private Thread thread;

    public WaitA(Thread thread) {
        this.thread = thread;
    }

    @Override
    public void run() {
        System.out.println("怪獸 開始排隊");
        if (thread != null) {
            try {
                System.out.println("奧特曼 插隊");
                thread.join();
                Thread.sleep(2000);
                System.out.println("怪獸買到到了東西");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class WaitB extends Thread {

    @Override
    public void run() {
        System.out.println("奧特曼 在隊列中了");

        try {
            Thread.sleep(2000);
            System.out.println("奧特曼買到到了東西");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

運行結果

怪獸 開始排隊
奧特曼 插隊
奧特曼 在隊列中了
奧特曼買到到了東西
怪獸買到到了東西

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章