当前位置 : 主页 > 编程语言 > c++ >

代码运行结束后没有正常退出

来源:互联网 收集:自由互联 发布时间:2021-07-03
一个多线程的实例代码,控制台可以正常输出结果4,但是没有输出“Process finished with exit code 0”,表明程序没有退出,这是什么原因? public class CyclicBarrierTest implements Runnable { private
一个多线程的实例代码,控制台可以正常输出结果4,但是没有输出“Process finished with exit code 0”,表明程序没有退出,这是什么原因?
public class CyclicBarrierTest implements Runnable {
    private CyclicBarrier cyclicBarrier = new CyclicBarrier(4, this);
    private Executor executor = Executors.newFixedThreadPool(4);
    private ConcurrentMap
 
   concurrentMap = new ConcurrentHashMap<>();

    private void calculate() {
        for (int i = 0; i < 4; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    concurrentMap.put(Thread.currentThread().getName(), 1);
                    try {
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CyclicBarrierTest cyclicBarrierTest = new CyclicBarrierTest();
        cyclicBarrierTest.calculate();
        Thread.sleep(1000);
        System.out.println(cyclicBarrierTest.concurrentMap.get("result"));
    }

    @Override
    public void run() {
        Integer result = 0;
        for (Map.Entry
  
    entry : concurrentMap.entrySet()) { result += entry.getValue(); } concurrentMap.put("result", result); } }
  
 
网友评论