[-]程序中调用join方法()
在程序中共有两个线程,一个是main()另一个是t1,在程序运行至ti.join()之前,两个线程的运行时同时的,但是当调用了该方法之后,随后就一直运行线程t1直到该线程运行完毕。如上述结果中在第十行调用了join()方法。
该无参数的方法,直到调用该方法的线程全部运行完毕之后才会运行其他的线程。
join(long millis)和join(long millis,int nanos),[第一个只有一个毫秒,第二个精确到纳秒] 就是调用该方法的线程执行时间,也就是其他线程等待的时间。
从上面的代码中可以看出,join将线程t1并入main中,在main中执行,直到t1执行完毕,再继续运行main线程。
【注】:
public class TestJoin {
……
Thread t1;
t1.start();
try{
t1.join();}catch(){}
……
}
class MyThread extends Thread{
public void run(){
………………
}
在没有执行t1.start()之前,只有main主线程在执行,运行至t1.start()之后,两个线程并发,在try块中t1.join()在此将两个进程合为一个,但是在合并之前,t1.join()要将t1的run()全部运行完毕之后或者完成join()内规定的时间才可以继续执行在main()终止处继续执行下面的代码。【具体如图】
具体代码以及输出结果:
1 package Test; 2 3 public class TestJoin { 4 public static void main(String[] args) { 5 MyThread2 t1 = new MyThread2("Stone"); 6 // main 主线程运行 7 8 t1.start();//两个线程都在运行 9 try{ 10 t1.join(); 11 // main()线程被终止,继续运行t1,直到t1运行完毕。 12 }catch(InterruptedException e){} 13 14 for(int i = 0;i<10;i++) 15 System.out.println("It is a main thread."+i); 16 } 17 } 18 19 class MyThread2 extends Thread { 20 MyThread2(String str) { 21 super(str); 22 } 23 24 public void run() { 25 for(int i = 0;i<10;i++){ 26 System.out.println("I am "+getName()+' '+ i); 27 try{ 28 sleep(1000); 29 30 }catch(InterruptedException e){ 31 return; 32 } 33 34 } 35 } 36 } 37 38 39 I am Stone 0 40 I am Stone 1 41 I am Stone 2 42 I am Stone 3 43 I am Stone 4 44 I am Stone 5 45 I am Stone 6 46 I am Stone 7 47 I am Stone 8 48 I am Stone 9 49 It is a main thread.0 50 It is a main thread.1 51 It is a main thread.2 52 It is a main thread.3 53 It is a main thread.4 54 It is a main thread.5 55 It is a main thread.6 56 It is a main thread.7 57 It is a main thread.8 58 It is a main thread.9 View Code
转载于:https://www.cnblogs.com/plxx/p/3369576.html