Thread类中的join方法的功能就是使异步执行的线程变成同步执行。
thread.join()应该是让其它线程进入阻塞状态,等当前的thread执行完之后,才允许其它线程执行 。
例:
- /**
-
* 线程的join举例.
-
* @version V1.0 ,2011-4-1
-
* @author xiahui
-
*/
-
public class JoinThread extends Thread
-
{
-
private int count=0;
-
-
public void run(){
-
while (true){
-
System.out.println(this.getName()+(++count));
-
try{
-
sleep(300);
-
}catch(InterruptedException ex){
-
}
-
if(count == 3)
-
return;
-
}
-
}
-
-
public static void main(String[] args) throws Exception
-
{
-
JoinThread counter1= new JoinThread();
-
JoinThread counter2 = new JoinThread();
-
JoinThread counter3 = new JoinThread();
-
-
counter1.setName("counter1_");
-
counter2.setName("counter2_");
-
counter3.setName("counter3_");
-
-
counter1.start();
-
counter2.start();
-
counter3.start();
-
}
-
-
}
输出结果
- counter1_1
-
counter3_1
-
counter2_1
-
counter1_2
-
counter3_2
-
counter2_2
-
counter1_3
-
counter2_3
-
counter3_3
从结果可以看出,三个线程是异步执行的,输出的次序是无序的
现在要求三个线程依次执行
- counter1.start();
-
counter1.join(); //等待counter1结束,其它线程才能执行
-
counter2.start();
-
counter2.join();//等待counter2结束,其它线程才能执行
-
counter3.start();
输出结果
- counter1_1
-
counter1_2
-
counter1_3
-
counter2_1
-
counter2_2
-
counter2_3
-
counter3_1
-
counter3_2
-
counter3_3
参考文献
1.
阅读(983) | 评论(0) | 转发(0) |