实例如下:
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(); //这句代码 建议放在 finally里执行 System.out.println(Thread.currentThread().getName() + "结束. 还有" + threadsSignal.getCount() + " 个线程"); } } }
以上这篇Java实现监控多个线程状态的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。