一、作用
Thread類中的join方法的主要作用就是同步,它可以使得線程之間的併發執行變爲串行執行。代碼實例如下:
public class ThreadDemo{
public void static main(String[] args){
// jdk1.8之後才具有這個功能
Runnable r=() -> {
Thread thd=Thread.currentThread();
System.out.println(thd.getName());
};
Thread thd1=new Thread(r);
Thread thd2=new Thread(r);
thd1.start();
//無期限的等待下去,直到thd1執行結束
thd1.join();
thd2.start();
}
}
上面這段代碼的意思是 :main主線程會等待thd1線程執行,當thd1線程執行結束之後,纔會繼續執行main主線程。
上面註釋也大概說明了join方法的作用:在A線程中調用了B線程的join()方法時,表示只有當B線程執行完畢時,A線程才能繼續執行。注意,這裏調用的join方法是沒有傳參的,join方法其實也可以傳遞一個參數給它的,具體看下面的簡單例子:
//等待10毫秒
thd1.join(10);
只有線程start()之後,join()方法纔會有效