gpt4 book ai didi

java - Executors.newSingleThreadExecutor 的后续调用之间的线程安全

转载 作者:搜寻专家 更新时间:2023-11-01 02:26:26 25 4
gpt4 key购买 nike

我有一个关于使用单线程执行器的问题。因为它重用了同一个线程,这是否意味着如果我在一次提交调用中修改了一个对象状态,我是否可以假设在后续的提交调用中对该对象状态的另一次修改是线程安全的?让我举个玩具例子...

public class Main {

public static void main(String[] args) throws Exception {

final A a = new Main().new A();
ExecutorService executor = Executors.newSingleThreadExecutor();

Callable<Integer> callable = new Callable<Integer>() {

@Override
public Integer call() throws Exception {
return a.modifyState();
}
};

/* first call */
Future<Integer> result = executor.submit(callable);
result.get();

/* second call */
result = executor.submit(callable);
int fin = result.get();
System.out.println(fin);

executor.shutdown();
}

class A {

private int state;

public int modifyState() {
return ++state;
}

public int getState() {
return state;
}

}
}

所以我正在共享对象 A。我提交一个可调用对象并首先修改它的状态(参见/* first call /)。然后我再做一次提交调用,再次修改 A 状态。 (/ 第二次调用 */)。现在我的大问题

可以这么说吗,因为它是同一个线程,所以第二次提交调用会将 A.state 视为 1?或者在某些情况下它也可以将其视为 0 吗?

所以基本上我想问的是,在单个线程执行程序的后续提交调用中修改未标记为 volatile /从同步块(synchronized block)访问的变量是否安全?,因为它重用了同一个线程

对于执行者来说,线程重用到底意味着什么?在单线程执行器的情况下,它真的是操作系统级别的同一个线程吗?

最佳答案

其实单线程也无所谓。 ExecutorService 的 javadoc状态:

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().

关于java - Executors.newSingleThreadExecutor 的后续调用之间的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21974093/

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