服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java实现监控多个线程状态的简单实例

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

2020-08-23 15:21Java之家 Java教程

下面小编就为大家带来一篇Java实现监控多个线程状态的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

实例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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实现监控多个线程状态的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐