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

网友投稿 233 2023-06-05


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

实例如下:

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExQbKbAdAecutor;

import java.util.concurrent.Executors;

/**

* 测试监控类

*

* @author

*

*/

public class WatchThread {

/**

* 测试函数

*

* @throws InterruptedException

*/

public void testThread() throws InterruptedException {QbKbAdA

int threadNQbKbAdAum = 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 http://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(); //这句代码 建议放在 finally里执行

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

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

}

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java中&与&&的区别
下一篇:spring data jpa分页查询示例代码
相关文章

 发表评论

暂时没有评论,来抢沙发吧~