[TOC]
事情的全部起因来自于这样一个程序
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
| public class VolatileTest { public static volatile int race = 0;
public static void increase(){ race++; }
private static final int THREADS_COUNT = 10;
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 < 10;i++){ increase(); } } }); threads[i].start(); }
while (Thread.activeCount() > 1){ System.out.println(Thread.activeCount()); Thread.yield(); } System.out.println(race); } }
|
这是一个简单的多线程下的计数器,用于说明volatile修饰的变量并不能完全解决多线程并发问题,体现在这段代码中就是最后打印的结果有可能<100。
这篇博文的主题不是讨论volatile关键字的用法,而是你如果在linux下跑这段程序,会卡在死循环了出不来,各种百度,google,总算找到了问题,我们先来看一看,简单启动一个main程序时,有多少个线程被创建呢?
1 2 3 4 5 6 7 8 9 10
| ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false,false);
for (ThreadInfo info : threadInfos ) { System.out.println("[" + info.getThreadId() + "]" + info.getThreadName()); }
System.out.println(Thread.activeCount());
|
文章参考:https://www.jianshu.com/p/2cfd551055d7
文章参考:https://www.zhihu.com/question/59297272/answer/164163911