This article mainly studies the use of join methods in Java multithreading. The following article is a specific example.
Thread's non-static method join() allows one thread B to "join" to the tail of another thread A. B cannot work until A has completed execution. For example:
Thread t = new MyThread();
t.start();
t.join();
In addition, the join() method has an overloaded version with a timeout limit. For example, t.join(5000); let the thread wait 5000 milliseconds. If this time exceeds this time, it stops waiting and becomes a runnable state.
The result of joining the thread join() on the thread stack is that the thread stack changes, and of course these changes are instantaneous.
public class TestJoin {public static void main(String[] args) {MyThread2 t1 = new MyThread2("TestJoin");t1.start();try {t1.join();//join() merge threads. Only after the child thread is running, the main thread starts executing}catch (InterruptedException e) {}for (int i=0 ; i <10; i++)System.out.println("I am Main Thread");}}class MyThread2 extends Thread {MyThread2(String s) {super(s);}public void run() {for (int i = 1; i <= 10; i++) {System.out.println("I am "+getName());try {sleep(1000);//Pause, output once every second}catch (InterruptedException e) {return;}}}}}Program running results:
I am TestJoin
I am TestJoin
I am TestJoin
I am TestJoin
I am TestJoin
I am TestJoin
I am TestJoin
I am TestJoin
I am TestJoin
I am TestJoin
I am Main Thread
I am Main Thread
I am Main Thread
I am Main Thread
I am Main Thread
I am Main Thread
I am Main Thread
I am Main Thread
I am Main Thread
I am Main Thread
The above is all the content of this article about the example code of Java multithreaded join method, and I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!