Posted on 2010-10-15 20:28
myfavorite 閱讀(1437)
評論(0) 編輯 收藏
場景:需要啟動多線程處理事情,而在所有事情做完之后,需要修改系統狀態;那么如何判斷所有線程(事情)都做完了呢?這就需要判斷所有當前運行的線程狀態了。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/**
* 測試監控類
*
* @author
*
*/
public class WatchThread {
/**
* 測試函數
*
* @throws InterruptedException
*/
public void testThread() throws InterruptedException {
int threadNum = 10;
// 初始化countDown
CountDownLatch threadSignal = new CountDownLatch(threadNum);
// 創建固定長度的線程池
Executor executor = Executors.newFixedThreadPool(threadNum);
for (int i = 0; i < threadNum; i++) { // 開threadNum個線程
Runnable task = new TestThread(threadSignal);
// 執行
executor.execute(task);
}
threadSignal.await(); // 等待所有子線程執行完
// do work
System.out.println(Thread.currentThread().getName() + "+++++++結束.");
}
/**
* 測試函數
*/
public static void main(String[] args) throws InterruptedException {
WatchThread test = new WatchThread();
test.testThread();
}
/**
*
* @author jill
*
*/
private class TestThread implements Runnable {
private CountDownLatch threadsSignal;
public TestThread(CountDownLatch threadsSignal) {
this.threadsSignal = threadsSignal;
}
public void run() {
System.out.println(Thread.currentThread().getName() + "開始
");
// do shomething
System.out.println("開始了線程::::" + threadsSignal.getCount());
// 線程結束時計數器減1
threadsSignal.countDown();
System.out.println(Thread.currentThread().getName() + "結束. 還有"
+ threadsSignal.getCount() + " 個線程");
}
}
}