Java multi threaded join method instance code

  • 2021-01-22 05:06:39
  • OfStack

This paper mainly studies the use of join method in Java multithreading. The following is a specific example.

The non-static method join() of Thread "joins" one thread B to the end of another thread A. B will not work until A has been executed. Such as:

[

Thread t = new MyThread();
t.start();
t.join();

]

In addition, join() There are also overloaded versions of methods with timeouts. For example, t.join(5000); The thread is made to wait 5000 milliseconds, and if this time is exceeded, it stops waiting and becomes runnable.

Addition of Threads join() The result is a change in the thread stack, 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. After the child threads finish 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, every 1 A second output 1 time 
			}
			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

]

conclusion

This article is about the Java multi-threaded join method example code all content, hope to help you. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!


Related articles: