gpt4 book ai didi

java - 创建和加入线程时副作用的可见性

转载 作者:搜寻专家 更新时间:2023-11-01 01:47:10 24 4
gpt4 key购买 nike

当没有同步块(synchronized block)和 volatile 变量时,一个线程执行的写入何时对另一个线程可见?这是一个简化的快速排序示例:

int middle = partitionForTheFirstTime(array);

Thread t = new Thread(new Quicksorter(array, 0, middle - 1));
Thread u = new Thread(new Quicksorter(array, middle + 1, array.size - 1));

t.start()
u.start();

t.join();
u.join();

(为简单起见,假设两个“工作线程”不产生任何额外的线程。)

加入两个线程是否保证当前线程看到它们的所有副作用?


相关说明,如果我在初始分区之前创建线程会发生什么情况?

Quicksorter a = new Quicksorter();
Quicksorter b = new Quicksorter();

Thread t = new Thread(a);
Thread u = new Thread(b);

int middle = partitionForTheFirstTime(array);

a.setParameters(array, 0, middle - 1);
b.setParameters(array, middle + 1, array.size - 1);

t.start()
u.start();

t.join();
u.join();

这两个线程是否能够看到由 partitionForTheFirstTime() 引起的副作用?换句话说,创建一个线程是否会产生先行关系,或者开始一个线程?

最佳答案

来自 section 17.4.5 of the JLS :

It follows from the above definitions that:

  • An unlock on a monitor happens-before every subsequent lock on that monitor.
  • A write to a volatile field (§8.3.1.4) happens-before every subsequent read of that field.
  • A call to start() on a thread happens-before any actions in the started thread.
  • All actions in a thread happen-before any other thread successfully returns from a join() on that thread.
  • The default initialization of any object happens-before any other actions (other than default-writes) of a program.

关于 start()join() 的部分与您相关 - 换句话说,当您join()-ed 线程成功,您会看到该线程中的所有操作。如果您 start() 一个线程,该新线程将看到调用 start() 的线程中已经发生的所有操作。

编辑:另见 "memory consistency errors" .

关于java - 创建和加入线程时副作用的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6263821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com