Java多線程中join方法的理解


thread.Join把指定的線程加入到當前線程,可以將兩個交替執行的線程合並為順序執行的線程。比如在線程B中調用了線程A的Join()方法,直到線程A執行完畢后,才會繼續執行線程B。

t.join();      //使調用線程 t 在此之前執行完畢。
t.join(1000);  //等待 t 線程,等待時間是1000毫秒

 

先上一段JDK中代碼:

 public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

 

 從代碼上看,如果線程被生成了,但還未被起動,調用它的 join() 方法是沒有作用的,將直接繼續向下執行

 

Join方法實現是通過wait(小提示:Object 提供的方法)。 當main線程調用t.join時候,main線程會獲得線程對象t的鎖(wait 意味着拿到該對象的鎖),調用該對象的wait(等待時間),直到該對象喚醒main線程 ,比如退出后。這就意味着main 線程調用t.join時,必須能夠拿到線程t對象的鎖

 

public class JoinTest {

    public static void main(String[] arg) throws InterruptedException {

        Thread1 t1=new Thread1();
        Thread2 t2=new Thread2();

        t1.start();
        t2.start();
        t1.join();
        //t2.start();

        System.out.println("主線程");
    }

    public static class Thread1 extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (Exception e) {


            }
            sayHello(this);

        }
    }

    public static class Thread2 extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {


            }
            sayHello(this);

        }
    }
    public static void sayHello(Object o){
        System.out.println("公用方法"+o.getClass().getName());
    }

}

說明:從源碼中可以看出,join(),其實是調用了wait()方法,wait方法是不會阻塞線程的,而sleep是會阻塞線程。當主線程等待的時候,並沒有影響t2的運行,所以t2正常打印。

wait()和sleep()的區別可以用這樣一個圖表示


免責聲明!

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



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