一聚教程网:一个值得你收藏的教程网站

热门教程

Java实现监控多个线程状态的简单实例

时间:2022-06-29 01:33:11 编辑:袖梨 来源:一聚教程网

 

 代码如下复制代码

importjava.util.concurrent.CountDownLatch;

importjava.util.concurrent.Executor;

importjava.util.concurrent.Executors;

 

/**

 * 测试监控类

 *

 * @author

 *

 */

publicclassWatchThread {

 

 /**

 * 测试函数

 *

 * @throws InterruptedException

 */

 publicvoidtestThread()throwsInterruptedException {

 intthreadNum =10;

 // 初始化countDown

 CountDownLatch threadSignal =newCountDownLatch(threadNum);

 // 创建固定长度的线程池

 Executor executor = Executors.newFixedThreadPool(threadNum);

 for(inti =0; i < threadNum; i++) {// 开threadNum个线程

  Runnable task =newTestThread(threadSignal);

  // 执行

  executor.execute(task);

 }

 threadSignal.await();// 等待所有子线程执行完

 // do work

 System.out.println(Thread.currentThread().getName() +"+++++++结束.");

 }

 

 /**

 * 测试函数

 */

 publicstaticvoidmain(String[] args)throwsInterruptedException {

 WatchThread test =newWatchThread();

 test.testThread();

 }

 

 /**

 *

 * @author jill

 *

 */

 privateclassTestThreadimplementsRunnable {

 privateCountDownLatch threadsSignal;

 

 publicTestThread(CountDownLatch threadsSignal) {

  this.threadsSignal = threadsSignal;

 }

 

 publicvoidrun() {

  System.out.println(Thread.currentThread().getName() +"开始...");

  // do shomething

  System.out.println("开始了线程::::"+ threadsSignal.getCount());

  // 线程结束时计数器减1

  threadsSignal.countDown(); //这句代码 建议放在 finally里执行

  System.out.println(Thread.currentThread().getName() +"结束. 还有"

   + threadsSignal.getCount() +" 个线程");

 }

 }

 

}

 

热门栏目