写多线程的时候,想要等main中其他线程都执行完成后(其他线程功能为对一个数字inc+1),输出最终的inc值。
于是写了个循环:
while (Thread.activeCount() > 1) {
System.out.println(Thread.activeCount());
Thread.yield();
}
System.out.println(test.inc);
结果进入了死循环
于是,main中只写已下代码:
System.out.println(Thread.activeCount()); // 结果为2
原因如下:
// 获取java线程的管理MXBean ThreadMXBean tmxb = ManagementFactory.getThreadMXBean(); // 不需要获取同步的Monitor和synchronizer信息,仅获取线程和线程堆栈信息 ThreadInfo[] threadInfos = tmxb.dumpAllThreads(false, false); // 遍历线程信息,打印出ID和名称 for (ThreadInfo info : threadInfos) { System.out.println("[" + info.getThreadId() + "] " + info.getThreadName()); }
[6] Monitor Ctrl-Break [5] Attach Listener [4] Signal Dispatcher [3] Finalizer [2] Reference Handler [1] main
System.out.println(Thread.activeCount());
Thread.currentThread().getThreadGroup().list();
2 java.lang.ThreadGroup[name=main,maxpri=10] Thread[main,5,main] Thread[Monitor Ctrl-Break,5,main]
可以发现当前线程组包含:main和Monitor Ctrl-Break
所有多线程测试代码如下:
import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** * java.util.concurrent.atomic包下提供了一些原子操作类,即对基本数据类型进行了封装,保证这些操作是原子性操作 * atomic是利用CAS来实现原子性操作的(Compare And Swap),CAS实际上是利用处理器提供的CMPXCHG指令实现的, * 而处理器执行CMPXCHG指令是一个原子性操作 * * @author Jack * @create 2018-05-04 12:12 **/ public class TestAtomicMain { private static final int THREAD_COUNT = 10; private static final int FOR_COUNT = 10; private static final int THREAD_ACTIVE_COUNT = 2; public AtomicInteger inc = new AtomicInteger(); public void increase() { inc.getAndIncrement(); } public static void main(String[] args) { final TestAtomicMain test = new TestAtomicMain(); ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); ThreadFactory namedThreadFactory = threadFactoryBuilder.setNameFormat("ThreadFactory-%d").build(); ExecutorService singleThreadPool = new ThreadPoolExecutor(THREAD_COUNT, THREAD_COUNT * 2, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); for (int i = 0; i < THREAD_COUNT; i++) { singleThreadPool.execute(() -> { for (int j = 0; j < FOR_COUNT; j++) { test.increase(); } }); } singleThreadPool.shutdown(); while (Thread.activeCount() > THREAD_ACTIVE_COUNT) { System.out.println("其他活跃的线程数" + Thread.activeCount()); Thread.yield(); } System.out.println(test.inc); } }
其他活跃的线程数9
其他活跃的线程数3
其他活跃的线程数3
100
达到预期效果
---------------------
原文:https://blog.csdn.net/ke_g3/article/details/80199209