歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java的join方法

Java的join方法

日期:2017/3/1 9:38:02   编辑:Linux編程

在某個線程中調用另一個線程的join方法,是將當前的cpu讓給另一個線程,等到規定的時間到了或另一個線程執行結束後,自己再執行

package test;

public class TestJoin1 {

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

TheOtherThread tot = new TheOtherThread();
Thread t = new Thread(tot);
t.start();
//t.join();
System.out.println("main");
}

}


class TheOtherThread implements Runnable{

@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
System.out.println(i);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

上面的結果會是

main
0
1
2
3
4
5
6
7
8
9

將t.join()前面的注釋去掉後結果會是

0
1
2
3
4
5
6
7
8
9
main

第二個例子

package test;

import java.util.Date;

public class TestJoin {

public static void main(String[] args) {

DateThreat dt1 = new DateThreat("a");
DateThreat dt2 = new DateThreat("b");

Thread t1 = new Thread(dt1);
Thread t2 = new Thread(dt2);

DateThreat dt3 = new DateThreat("c",t2);
Thread t3 = new Thread(dt3);


t1.start();
t2.start();
t3.start();

}

}

class DateThreat implements Runnable{

private String name ;

private Thread t;

public DateThreat(String name) {
this.name = name;
}

public DateThreat(String name,Thread t) {
this.name = name;
this.t = t;
}

@Override
public void run() {

try {
System.out.println(this.name + " begin : " + new Date());
if(t != null){
t.join();
}
for(int i =0;i<10;i++){
Thread.sleep(1000);
System.out.println(this.name + " : " + i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.name + " end : " + new Date());

}


}

a,b,c三個線程幾乎同時開始,但c永遠是在b執行結束後才開始執行

結果會是:

c begin : Tue Aug 12 17:59:16 CST 2014
b begin : Tue Aug 12 17:59:16 CST 2014
a begin : Tue Aug 12 17:59:16 CST 2014
b : 0
a : 0
b : 1
a : 1
b : 2
a : 2
b : 3
a : 3
b : 4
a : 4
b : 5
a : 5
b : 6
a : 6
b : 7
a : 7
b : 8
a : 8
b : 9
b end : Tue Aug 12 17:59:26 CST 2014
a : 9
a end : Tue Aug 12 17:59:26 CST 2014
c : 0
c : 1
c : 2
c : 3
c : 4
c : 5
c : 6
c : 7
c : 8
c : 9
c end : Tue Aug 12 17:59:36 CST 2014

可以多運行幾遍

Java中介者設計模式 http://www.linuxidc.com/Linux/2014-07/104319.htm

Java 設計模式之模板方法開發中應用 http://www.linuxidc.com/Linux/2014-07/104318.htm

設計模式之 Java 中的單例模式(Singleton) http://www.linuxidc.com/Linux/2014-06/103542.htm

Java對象序列化 http://www.linuxidc.com/Linux/2014-10/107584.htm

大話設計模式(帶目錄完整版) PDF+源代碼 http://www.linuxidc.com/Linux/2014-08/105152.htm

Copyright © Linux教程網 All Rights Reserved