Java Thread join方法可以用来暂停当前的线程执行,除非指定的线程已死。
Java Thread 加入
public final void join(): This java thread join method puts the current thread on wait until the thread on which it's called is dead. If the thread is interrupted, it throws InterruptedException. public final synchronized void join(long millis): This java thread join method is used to wait for the thread on which it's called to be dead or wait for specified milliseconds. Since thread execution depends on OS implementation, it doesn't guarantee that the current thread will wait only for given time. public final synchronized void join(long millis, int nanos): This java thread join method is used to wait for thread to die for given milliseconds plus nanoseconds. Here is a simple example showing usage of Thread join methods. The goal of the program is to make sure main is the last thread to finish and third thread starts only when first one is dead.
1package com.journaldev.threads;
2
3public class ThreadJoinExample {
4
5 public static void main(String[] args) {
6 Thread t1 = new Thread(new MyRunnable(), "t1");
7 Thread t2 = new Thread(new MyRunnable(), "t2");
8 Thread t3 = new Thread(new MyRunnable(), "t3");
9
10 t1.start();
11
12 //start second thread after waiting for 2 seconds or if it's dead
13 try {
14 t1.join(2000);
15 } catch (InterruptedException e) {
16 e.printStackTrace();
17 }
18
19 t2.start();
20
21 //start third thread only when first thread is dead
22 try {
23 t1.join();
24 } catch (InterruptedException e) {
25 e.printStackTrace();
26 }
27
28 t3.start();
29
30 //let all threads finish execution before finishing main thread
31 try {
32 t1.join();
33 t2.join();
34 t3.join();
35 } catch (InterruptedException e) {
36 // TODO Auto-generated catch block
37 e.printStackTrace();
38 }
39
40 System.out.println("All threads are dead, exiting main thread");
41 }
42
43}
44
45class MyRunnable implements Runnable{
46
47 @Override
48 public void run() {
49 System.out.println("Thread started:::"+Thread.currentThread().getName());
50 try {
51 Thread.sleep(4000);
52 } catch (InterruptedException e) {
53 e.printStackTrace();
54 }
55 System.out.println("Thread ended:::"+Thread.currentThread().getName());
56 }
57
58}
上述方案的结果是:
1Thread started:::t1
2Thread started:::t2
3Thread ended:::t1
4Thread started:::t3
5Thread ended:::t2
6Thread ended:::t3
7All threads are dead, exiting main thread
这就是关于Java thread join的快速回合的例子。