且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么增加10个Java线程中的数字不会导致值10?

更新时间:2023-02-10 07:42:35

两个原因:

  1. 您不是在等待线程完成,而是在关闭线程池(即:导致线程池拒绝新任务,但继续处理现有任务).

  1. You're not waiting for the threads to finish, you're just shutting down the thread pool (that is: causing the thread pool to reject new tasks but continue to process existing tasks).

您没有在线程池中的写入与主线程中的读取之间建立先发生后关联.

You're not establishing a happens-before relationship between the writes in the thread pool and the read in the main thread.

您可以(通过其他方法)执行此操作:

You could do this by (amongst other methods):

  1. 在阅读 a ;
  2. 之前获取信号灯
  3. 通过使用 submit 而不是 execute 来为提交的每个任务获取 Future<?> ,并调用 Future.get()方法.它记录在 ExecutorService的Javadoc中 表示发生了一个事前发生.
  1. Acquiring the semaphore before reading a;
  2. By using submit instead of execute to get a Future<?> for each of the tasks submitted, and invoking the Future.get() method on all of the returned futures. It is documented in the Javadoc of ExecutorService that this establishes a happens-before.

第一点是主要"信息. a 出现为零的原因:如果我在本地运行它,并等待线程池终止,则 a 出现为10.

The first point is the "main" reason why a is coming out as zero: if I run it locally, and wait for the the thread pool to terminate, a comes out to 10.

但是,仅仅因为它出现10并不意味着代码可以正确工作而无需注意第二点:您需要应用Java内存模型来保证正确的功能.

However, just because it comes out as 10 doesn't mean the code works correctly without paying attention to the second point: you need to apply the Java Memory Model to have guarantees of correct functioning.