"Cannot reproduce" - Java 确定性多线程可能吗?

"Cannot reproduce" - is Java deterministic multithreading possible?

这是否可能以确定性方式 运行 多线程 Java 应用程序?我的意思是在我的应用程序的两个不同 运行 中总是有相同的线程切换。

这样做的原因是 运行 在每个 运行 中完全相同的条件下进行模拟。

类似的情况是当一个人在使用随机数生成器获得总是相同的 "random" 序列时给出一些任意种子。

我不知道有什么实用的方法可以做到这一点。

理论上,在某些假设下1 可以实现具有完全确定性行为的字节码解释器。您需要通过完全在软件中实现线程和线程调度并使用单个本机线程来模拟多个线程。


1 - 例如,没有 I/O,也没有使用系统时钟。

不,不可能(除了自己模拟)每次都以相同的方式使用多个线程交错。线程不是为这样做而设计的。

如果您想要确定性结果,请不要使用线程。

OldCurmudgeon 所述,多线程是不可能的。

如果您决定使用单个 Thread,我更喜欢 newSingleThreadExecutor 而不是普通的 Thread,因为 newSingleThreadExecutor

的灵​​活性和优势

使用

newSingleThreadExecutor 来自 Executors

public static ExecutorService newSingleThreadExecutor()

Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.)

Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.

相关 SE 问题:

Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()

ExecutorService vs Casual Thread Spawner