java--join方法

时间:2023-03-09 03:48:47
java--join方法
 package MyTest;

 class TestDemo implements Runnable {

     public void run() {
int i = 0;
for (int j = 0; j < 10; j++) {
System.out.println(Thread.currentThread().getName() + " ---> "
+ i++);
}
}
} public class Demo1 {
public static void main(String[] args) {
TestDemo testDemo = new TestDemo();
Thread t1 = new Thread(testDemo);
t1.start();
int i = 0;
for(int x = 0;x<10;x++){
if(i == 5){
try{
t1.join(1000);
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
}
System.out.println("main thread "+i++); }
}
}
 main thread 0
main thread 1
main thread 2
Thread-0 ---> 0
Thread-0 ---> 1
Thread-0 ---> 2
Thread-0 ---> 3
main thread 3
main thread 4
Thread-0 ---> 4
Thread-0 ---> 5
Thread-0 ---> 6
Thread-0 ---> 7
Thread-0 ---> 8
Thread-0 ---> 9
main thread 5
main thread 6
main thread 7
main thread 8
main thread 9

[-]程序中调用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(){

………………

}

java--join方法

在没有执行t1.start()之前,只有main主线程在执行,运行至t1.start()之后,两个线程并发,在try块中t1.join()在此将两个进程合为一个,但是在合并之前,t1.join()要将t1的run()全部运行完毕之后或者完成join()内规定的时间才可以继续执行在main()终止处继续执行下面的代码。【具体如图】

具体代码以及输出结果:

 package Test;

 public class TestJoin {
public static void main(String[] args) {
MyThread2 t1 = new MyThread2("Stone");
// main 主线程运行 t1.start();//两个线程都在运行
try{
t1.join();
// main()线程被终止,继续运行t1,直到t1运行完毕。
}catch(InterruptedException e){} for(int i = 0;i<10;i++)
System.out.println("It is a main thread."+i);
}
} class MyThread2 extends Thread {
MyThread2(String str) {
super(str);
} public void run() {
for(int i = 0;i<10;i++){
System.out.println("I am "+getName()+' '+ i);
try{
sleep(1000); }catch(InterruptedException e){
return;
} }
}
} I am Stone 0
I am Stone 1
I am Stone 2
I am Stone 3
I am Stone 4
I am Stone 5
I am Stone 6
I am Stone 7
I am Stone 8
I am Stone 9
It is a main thread.0
It is a main thread.1
It is a main thread.2
It is a main thread.3
It is a main thread.4
It is a main thread.5
It is a main thread.6
It is a main thread.7
It is a main thread.8
It is a main thread.9