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

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

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 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题
  • ¥15 Selenium+docker Chrome不能运行
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥50 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错