Java multi-thread join Method Instance code, java multi-thread join instance
This article focuses on the use of join methods in Java multithreading. The following is an example.
The non-static join () method of Thread allows A Thread B to "join" to the end of another Thread. Before Execution of A, B cannot work. For example:
Thread t = new MyThread ();
T. start ();
T. join ();
In addition,join()
The method also contains the overloaded version with the timeout limit. For examplet.join(5000);
The thread is waiting for 5000 milliseconds. If the time exceeds this time, the thread stops waiting and becomes runable.
Thread Additionjoin()
The result of the thread stack is that the thread Stack has changed. 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 thread. After the child thread is run, 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 result:
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
Summary
The above is all about the Java multi-threaded join Method Instance code in this article. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!