Java多線程之join


1.join方法只有在繼承了Thread類的線程中才有。

2.線程必須要start() 后再join才能起作用。

 

將另外一個線程join到當前線程,則需要等到join進來的線程執行完才會繼續執行當前線程。

package Thread.join;

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.println(getName() + " was interrupted."
                    + "isInterrupted():" + isInterrupted());
            return;
        }
        System.out.println(getName() + " has awakened");
    }
}

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.println("Interrupted");
        }
        System.out.println(getName() + " join completed");
    }
}

public class Joining {
    public static void main(String[] args) {
        Sleeper sleepy01 = new Sleeper("Sleepy01", 1500), sleepy02 = new Sleeper(
                "Sleepy02", 1500);
        Joiner joiner01 = new Joiner("Joiner01", sleepy01), joiner02 = new Joiner("Joiner02",
                sleepy02);
        joiner01.interrupt();

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM