Java 多线程进阶-并发编程(一) 线程组ThreadGroup
2021-02-13 11:20
标签:str 高度 操作 性能 sys port cti cond 消息 并行计算 线程组ThreadGroup Java 多线程进阶-并发编程(一) 线程组ThreadGroup 标签:str 高度 操作 性能 sys port cti cond 消息 原文地址:https://www.cnblogs.com/sweetXiaoma/p/12725897.htmlJava 多线程进阶-并发编程
(线程组只是提供一个数组的方式来控制线程. 线程和线程组中的线程都是 new 产生出来的, start 一次后, 就不能再次 start 了. new 的代价是很昂贵的, 只运行一次, 性价比过低.) package thread0411;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* 1. 依次启动十个线程放在一个线程组里, 每个线程随机完成若干时间的任务
* 23. 查看线程组状态
* 4. while检测是否十个线程都还在active状态, 如果是则阻塞.
* 5. 终止线程组中的所有线程.
*/
public class ThreadGroupDemo {
public static void main(String[] args) {
// 创建线程组
ThreadGroup threadGroup = new ThreadGroup("Searcher111");
// 创建一个任务, 10个线程完成
System.out.println(LocalDateTime.now() + " => " + "====== 1 子线程启动 ======");
Result result = new Result();
Searcher searchTask = new Searcher(result);
for (int i = 0; i " + "====== 2 查看线程组状态 ======");
System.out.printf(LocalDateTime.now() + " => " + "线程组当前 active 线程数量: %d" + "\n", threadGroup.activeCount());
System.out.println(LocalDateTime.now() + " => " + "线程组消息明细");
threadGroup.list();
System.out.println("");
// 遍历线程组
System.out.println(LocalDateTime.now() + " => " + "====== 3 遍历线程组 ======");
Thread[] threads = new Thread[threadGroup.activeCount()];
threadGroup.enumerate(threads); // 将线程组中的active的线程拷贝到数组中.
for (int i = 0; i " + "Thread %s: state: %s " + "\n", threads[i].getName(), threads[i].getState());
}
System.out.println("");
// 等待线程结束
System.out.println(LocalDateTime.now() + " => " + "====== 4 等待线程结束 ======");
// 循环检测是否所有线程都还在进行中...
while (threadGroup.activeCount() > 9) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("");
// 中断线程组中的所有线程
System.out.println(LocalDateTime.now() + " => " + "====== 5 中断线程组中的所有线程 ======");
threadGroup.interrupt();
}
}
class Result {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Searcher implements Runnable {
private Result result;
public Searcher(Result result) {
this.result = result;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.printf(LocalDateTime.now() + " => " + "Thread %s: 启动" + "\n", name);
try {
doTask();
result.setName(name);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.printf(LocalDateTime.now() + " => " + "Thread %s: 被中断\n", name);
return;
}
System.out.printf(LocalDateTime.now() + " => " + "Thread %s 完成\n", name);
}
// 模拟工作若干时间
void doTask() throws InterruptedException {
Random random = new Random(new Date().getTime());
int value = (int) (random.nextDouble() * 100);
System.out.printf(LocalDateTime.now() + " => " + "Thread %s: %d\n", Thread.currentThread().getName(), value);
TimeUnit.SECONDS.sleep(value); // 随机等待若干秒, 模拟进行工作
}
}
上一篇:Java 线程 面试题
文章标题:Java 多线程进阶-并发编程(一) 线程组ThreadGroup
文章链接:http://soscw.com/index.php/essay/54844.html