1. 现在有线程 T1、T2 和 T3。你如何确保 T2 线程在 T1 之后执行,并且 T3 线程在 T2 之后执行?
public class TestJoin { static class TestThread extends Thread { TestThread(String name) { setName(name); } @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { Thread t1 = new TestThread("线程1"); Thread t2 = new TestThread("线程2"); Thread t3 = new TestThread("线程3"); try { //t1先启动 t1.start(); t1.join(); //t2 t2.start(); t2.join(); //t3 t3.start(); t3.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
Java 7 Concurrency Cookbook 中对join的相关描述:
Waiting for the finalization of a thread
In some situations, we will have to wait for the finalization of a thread. For example, we may have a program that will begin initializing the resources it needs before proceeding with the rest of the execution. We can run the initialization tasks as threads and wait for its finalization before continuing with the rest of the program. For this purpose, we can use the join() method of the Thread class. When we call this method using a thread object, it suspends the execution of the calling thread until the object called finishes its execution.
当我们调用某个线程的这个方法时,这个方法会挂起调用线程,直到被调用线程结束执行,调用线程才会继续执行。