本文實(shí)例講述了Java之Thread的join方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
join
public final void join()
throws InterruptedException等待該線程終止。
拋出:
InterruptedException - 如果任何線程中斷了當(dāng)前線程。當(dāng)拋出該異常時(shí),當(dāng)前線程的中斷狀態(tài) 被清除。
下面的例子 通俗的講,就是A調(diào)用join方法后,只有等A所在的線程不再運(yùn)行,才會(huì)將進(jìn)程分配出去
public class joinThread {
public static void main(String [] args) throws Exception{
ThreadTest5 t = new ThreadTest5();
Thread A = new Thread(t);
Thread B = new Thread(t);
A.start();
A.join(); //此處A調(diào)用 Thread的join方法,主函數(shù)將線程分配給A,當(dāng)A運(yùn)行完畢后,才會(huì)將線程釋放出去。給其他的對(duì)象。
B.start();
for (int i = 1;i < 20;i++)
{
System.out.println("樹(shù)上掉蘋(píng)果"+ i);
}
System.out.println("蘋(píng)果沒(méi)了");
}
}
class ThreadTest5 implements Runnable
{
public void run()
{
for (int i = 1;i < 10;i++)
{
System.out.println(Thread.currentThread().getName()+"吃蘋(píng)果"+(i));
}
}
}
運(yùn)行結(jié)果為:
Thread-0吃蘋(píng)果1
Thread-0吃蘋(píng)果2
Thread-0吃蘋(píng)果3
Thread-0吃蘋(píng)果4
Thread-0吃蘋(píng)果5
Thread-0吃蘋(píng)果6
Thread-0吃蘋(píng)果7
Thread-0吃蘋(píng)果8
Thread-0吃蘋(píng)果9
樹(shù)上掉蘋(píng)果1
樹(shù)上掉蘋(píng)果2
樹(shù)上掉蘋(píng)果3
樹(shù)上掉蘋(píng)果4
樹(shù)上掉蘋(píng)果5
樹(shù)上掉蘋(píng)果6
Thread-1吃蘋(píng)果1
樹(shù)上掉蘋(píng)果7
Thread-1吃蘋(píng)果2
樹(shù)上掉蘋(píng)果8
Thread-1吃蘋(píng)果3
樹(shù)上掉蘋(píng)果9
Thread-1吃蘋(píng)果4
樹(shù)上掉蘋(píng)果10
Thread-1吃蘋(píng)果5
樹(shù)上掉蘋(píng)果11
Thread-1吃蘋(píng)果6
Thread-1吃蘋(píng)果7
Thread-1吃蘋(píng)果8
Thread-1吃蘋(píng)果9
樹(shù)上掉蘋(píng)果12
樹(shù)上掉蘋(píng)果13
樹(shù)上掉蘋(píng)果14
樹(shù)上掉蘋(píng)果15
樹(shù)上掉蘋(píng)果16
樹(shù)上掉蘋(píng)果17
樹(shù)上掉蘋(píng)果18
樹(shù)上掉蘋(píng)果19
蘋(píng)果沒(méi)了
Thread-0 值得就是A所在的線程,當(dāng)A所在的線程運(yùn)行完畢后,之后的線程由main主函數(shù)和B進(jìn)程爭(zhēng)奪。
希望本文所述對(duì)大家的Java程序設(shè)計(jì)有所幫助。