博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
while(Thread.activeCount() > 1)
阅读量:7221 次
发布时间:2019-06-29

本文共 1027 字,大约阅读时间需要 3 分钟。

今天看到深入理解JVM第367页多线程volatile部分照着书本敲着代码发现了一个问题 Thread.activeCount()会一直大于2

public class VolatileTest {public static volatile int race = 0;public static void increase() {    race++;}private static final int THREADS_COUNT = 20;public static void main(String[] args) {    Thread[] threads = new Thread[THREADS_COUNT];    for (int i = 0; i < THREADS_COUNT; i++) {        threads[i] = new Thread(new Runnable() {            @Override            public void run() {                for (int i = 0; i < 10000; i++) {                    increase();                }            }        });        threads[i].start();    }    while (Thread.activeCount() > 1) {        Thread.yield();    }    System.out.println(race);}}

2yGJ4JE.png

陷入了死循环.......why?

Thread.yield();//应该主线程先让出cpu使用权

问题在这Thread.activeCount() 还有个守护线程!!!所以就会一直陷入无限循环。

加了一句Thread.currentThread().getThreadGroup().list();

while (Thread.activeCount() > 1) {        Thread.currentThread().getThreadGroup().list();        Thread.yield();    }

RcFOobv.png

转载于:https://www.cnblogs.com/rookieJW/p/9106003.html

你可能感兴趣的文章
ArcGIS Server 内存占用相关
查看>>
结对开发----找一
查看>>
我的Android进阶之旅------>Android项目目录结构分析
查看>>
linux下配置apache多站点访问-小案例
查看>>
B树等介绍
查看>>
iOS应用性能调优的25个建议和技巧
查看>>
Kotlin中使用简洁明了的代码替换findViewByid
查看>>
上边栏固定高,下边栏自适应
查看>>
一些优秀博客
查看>>
2013 Multi-University Training Contest 5 部分解题报告
查看>>
django学习笔记1
查看>>
01-1制作U盘启动盘--大白菜超级U盘启动盘制作工具
查看>>
springboot整合mybatis和mybatis-plus
查看>>
Spring IOC容器
查看>>
SB Admin 2 学习笔记1
查看>>
android Adapter剖析理解
查看>>
【纪中集训2019.3.20】铁路
查看>>
windos 2008 vista 下的端口范围改变
查看>>
request
查看>>
String
查看>>