Thread.join()練習

Thread.join()表示等待線程執行完畢,如下是代碼示例,簡單地等待兩個線程執行完畢。java

package org.com.jsoup;

public class ThreadJoinTest {

	/**
	 * @param args
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		// 開始時間
		long beginTime = System.nanoTime();

		Runnable runable = new Runnable() {
			@Override
			public void run() {
				try {
					// 排隊等待
					System.out
							.println(String.format("線程名稱:%s 當前時間:%d", Thread.currentThread()
									.getName(),System.nanoTime()));
					Thread.sleep(2000);
				} catch (Exception e) {
					// 處理異常
				} finally {
					// 減小計數值
				}
			}
		};
		// 將任務放入線程池執行
		Thread t = new Thread(runable);
		t.start();
		Thread t1 = new Thread(runable);
		t1.start();
		t.join();
		t1.join();
		System.out.println("執行完畢:" + (System.nanoTime() - beginTime));
	}

}
相關文章
相關標籤/搜索