Java的join方法

2014-11-23 18:58:56 · 作者: · 浏览: 30

在某个线程中调用另一个线程的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


可以多运行几遍