1. 程式人生 > >三個執行緒順序執行

三個執行緒順序執行

public class Test {
	public static void main(String[] args) throws InterruptedException {
		final Thread t1 = new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					Thread.sleep(5000);
					System.out.println(Thread.currentThread().getName());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"Thread-T1");
		final Thread t2 = new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					t1.join();
					Thread.sleep(3000);
					System.out.println(Thread.currentThread().getName());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"Thread-T2");
		final Thread t3 = new Thread(new Runnable(){
			@Override
			public void run() {
				try {
					t2.join();
					Thread.sleep(1000);
					System.out.println(Thread.currentThread().getName());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"Thread-T3");
		t3.start();
		t2.start();
		t1.start();
	}
}
thread.Join把指定的執行緒加入到當前執行緒,可以將兩個交替執行的執行緒合併為順序執行的執行緒。比如線上程B中呼叫了執行緒A的Join()方法,直到執行緒A執行完畢後,才會繼續執行執行緒B。