HLhakey 2017-08-16 07:38 采纳率: 100%
浏览 2622
已采纳

多线程静态变量累加求和 , 计算结果是对的,但是不明白为什么是对的.

package thread.worker;

/**
 * Created by huli3 on 2017/8/16.
 */
public class ExecutorTest {
    static int sum = 0;

    public static void main(String[] args) throws InterruptedException {
        ThreadGroup hl = new ThreadGroup("hl");
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(hl, new MyThread(hl));
            thread.start();
        }
        while (hl.activeCount() > 0) {
            Thread.currentThread().yield();
        }
        System.out.println(sum);
    }

    static class MyThread implements Runnable {
        ThreadGroup threadGroup;

        public MyThread(ThreadGroup threadGroup) {
            this.threadGroup = threadGroup;
        }

        public void run() {
            for (int j = 0; j < 4; j++) {
                sum++;
                System.out.println(threadGroup.activeCount() + " sum " + sum + "  and current thread is :" + "id:"+Thread.currentThread().getId());
            }
//            System.out.println(threadGroup.activeCount() + " sum " + sum + "  and current thread is :" + Thread.currentThread().getId());

        }
    }
}

  • 写回答

6条回答 默认 最新

  • 砸死接触 2017-08-16 13:22
    关注

    因为你用了volatile 修饰变量啊,所以线程里的每次取值都是新的,但是你的System.out.println()打印比较低效,所以会有看起来乱的现象

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?