執行緒的join和yield
阿新 • • 發佈:2019-02-15
join()方法的理解
這是官方文件的註釋:
/**
* Waits for this thread to die.
*
* <p> An invocation of this method behaves in exactly the same
* way as the invocation
*
* <blockquote>
* {@linkplain #join(long) join}{@code (0)}
* </blockquote>
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public final void join() throws InterruptedException {
join(0);
}
join()方法的作用:Waits for this thread to die.即:等待這個執行緒結束。
我們可以看個demo
package com.example.demo.threadpool;
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread.sleep(300 );
Thread thread1 = new Thread(() -> {
System.out.println(Thread.currentThread().getName());
}, "thread1");
Thread thread2 = new Thread(() -> {
System.out.println(Thread.currentThread().getName());
}, "thread2");
Thread thread3 = new Thread(() -> {
System.out.println(Thread.currentThread().getName());
}, "thread3");
thread2.start();
thread2.join();
thread1.start();
thread1.join();
thread3.start();
thread3.join();
// Thread.currentThread().yield();
System.out.println("main:" + Thread.currentThread().getName());
}
}
大家可以猜猜結果 如果沒有join 結果又會怎麼樣呢?
根據程式碼中的定義 只有 thread2 執行完畢後 才會執行thread1 然後接著才是thread3 最後才是主執行緒 如果沒有join() 那麼結果就是隨機的。
這是程式碼的執行結果 :
**
**thread2
thread1
thread3
main:main****
關於yield:
簡單說下,這個方法大家瞭解就行,不實用,在多執行緒裡面有各種各樣的方法,其中有一個禮讓 的方法很有意思,現實生活中所謂的禮讓,就是“委屈自己方便他人”!比如過馬路,汽車禮讓行人,當然這是在國外吐舌頭,國內過個斑馬線是要看司機的性格的!那麼線上程中是個什麼情況呢,下面看一下demo(同上程式碼 把join去掉就行了)
結果可能會出乎意料哦
yield這個方法只會去告訴排程器 你該讓出時間片了 讓別的執行緒去跑會 然後任務排程器可不一定會聽它的 所有它的結果也是不確定的。