線程入門——加入一個線程

示例:this

/**
 * Created by Administrator on 2017/9/4.
 */

class Sleeper extends Thread {
    private int duration;

    public Sleeper(String name, int sleepTime) {
        super(name);
        duration = sleepTime;
        start();
    }

    public void run() {
        try {
            sleep(duration);
        } catch (InterruptedException e) {
            System.out.print(getName() + " was interrupted." + " isInterrupted():" + isInterrupted() + "\r\n");
            return;
        }
        System.out.print(getName() + " has awakened" + "\r\n");
    }
}

class Joiner extends Thread {
    private Sleeper sleeper;

    public Joiner(String name, Sleeper sleeper) {
        super(name);
        this.sleeper = sleeper;
        start();
    }

    public void run() {
        try {
            sleeper.join();
        } catch (InterruptedException e) {
            System.out.print("InterruptedException" + "\r\n");
        }
        System.out.print(getName() + " join completed" + "\r\n");
    }
}


public class Joining {
    public static void main(String[] args) {
        Sleeper sleepy = new Sleeper("Sleepy", 1500);
        Sleeper grumpy = new Sleeper("Grumpy", 1500);

        Joiner dopey = new Joiner("Dopey", sleepy);
        Joiner doc = new Joiner("Doc", grumpy);
        grumpy.interrupt();
    }
}

 

一個線程能夠在其餘線程之上調用join()方法,其效果是等待一段時間直到第二個線程結束才能繼續執行。若是某個線程在另外一個線程t上調用t.join(),此線程將被掛起,直到目標線程結束才能恢復(即t.isAlive()返回爲假)也能夠在調用join()時帶上一個超時參數(單位能夠是毫秒,或者毫秒和納秒),這樣若是目標線程在這段時間到期時尚未結束的話,join()方法總能返回。線程

對join()方法的調用能夠被中斷,作法是在調用線程上調用interrupt()方法,這時須要用到try-catch語句。對象

Sleeper是一個Thread類型,它要休眠一段時間。這段時間是經過構造器傳進來的參數所指定的。在run()中,sleep()方法有可能在指定的時間期滿時返回,但也可能被中斷。在catch子句中,將根據isInterrupted()的返回值報告這個中斷。當另外一個線程在該 線程上調用interrupt()時,將給該線程設定一個標誌,代表該線程已經被中斷。然而,異常被捕獲時將清理這個標誌,因此在catch子句中,在異常被捕獲的時侯這個標誌老是爲假。除異常以外,這個標誌還可用於其餘狀況,好比線程可能會檢查其中斷狀態。get

Joiner線程將經過在Sleeper對象上調用Join()方法來等待sleeper原本。在main()裏面,每一個Sleeper都有一個Joiner,能夠在輸出中發現,若是Sleeper被中斷或者是正常結束,Joiner將和Sleeper一同結束。io

相關文章
相關標籤/搜索