java - 一个简单多线程资源共享问题,不明白为什么会出现奇数结果

 欢迎bm访问老年人空间 发布于 2022-10-28 23:23

代码为下面:

  1. 为什么运行会出现奇数结果? 《java编程思想》的里面的解释没有看懂,能够请大神解释一下其中原理。

import java.util.concurrent.*;

public class EvenGenerator extends IntGenerator {
  private int currentEvenValue = 0;
  public int next() {
    ++currentEvenValue; // Danger point here!
    ++currentEvenValue;
    return currentEvenValue;
  }
  public static void main(String[] args) {
    EvenChecker.test(new EvenGenerator() ,10);
  }
} 
public class EvenChecker implements Runnable {
  private IntGenerator generator;
  private final int id;
  public EvenChecker(IntGenerator g, int ident) {
    generator = g;
    id = ident;
  }
  public void run() {
    while(!generator.isCanceled()) {
      int val = generator.next();
    //   System . out . println ( val ) ;         
      if(val % 2 != 0) {
        System.out.println(val + " not even!");
        generator.cancel(); // Cancels all EvenCheckers
      }
    }
  }
  // Test any type of IntGenerator:
  public static void test(IntGenerator gp, int count) {
    System.out.println("Press Control-C to exit");
    ExecutorService exec = Executors.newCachedThreadPool();
    for(int i = 0; i < count; i++)
      exec.execute(new EvenChecker(gp, i));
    exec.shutdown();
  }
 
  }
}
2 个回答
  • 多条线程交叉执行,修改变量currentEvenValue,执行++currentEvenValue操作,currentEvenValue可能的值可以为,2、3、4、5、6、7、8、9、10、11、12、13.。。。,而且对于java来说,int类型的变量,是否为原子操作、线程操作是否安全,估计是不确定的,这样交叉操作currentEvenValue,很可能出现异常。

    2022-10-30 04:20 回答
  • 第一个问题, 因为i++不是原子操作,stackOverflow回答
    第二个问题, 是因为你试的次数不多。

    2022-10-30 04:22 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有