java - 任何单线程程序如何成为有效的多线程程序?

标签 java multithreading concurrency thread-safety

我正在阅读《Java 并发实践》这本书。在第二章,我读了声明

any single-threaded program is also a valid multithreaded program

我无法理解这种说法。

请分享您对此的想法,以便消除我的困惑。提前致谢。

最佳答案

请注意,该声明并不意味着任何正确的单线程程序也是正确的多线程程序,作者只是声明可以将任何单线程程序转换为在多线程环境中执行。

但是,如果程序在单线程环境中已经不正确,那么它不可能在更复杂的多线程环境中正确。

摘自本书:

Since any single threaded program is also a valid multithreaded program, it cannot be thread safe if it is not even correct in a single threaded environment.

If an object is correctly implemented, no sequence of operations-calls to public methods and reads or writes of public fields should be able to violate any of its invariants or post conditions. No set of operations performed sequentially or concurrently on instances of a thread safe class can cause an instance to be in an invalid state.

还有这个:

If the loose use of "correctness" here bothers you, you may prefer to think of a thread safe class as one that is no more broken in a concurrent environment than in a single threaded environment.

@yshavit 在开始考虑多线程正确性之前,请确保您至少具有单线程正确性。

关于java - 任何单线程程序如何成为有效的多线程程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42674831/

相关文章:

java - Itext 签名空签名字段

c# - ConcurrentDictionary 陷阱 - 来自 GetOrAdd 和 AddOrUpdate 的委托(delegate)工厂是否同步?

c# - 在 form.show 之后让主线程在按下按钮时执行代码

.net - NEventStore乐观锁

c++ - 如何异步运行整个 QApplication?

php - 教义中的并发

java - 使用 FTPS 将文件从 AS400 调度到大型机

java - Tomcat SecretKeyCredentialHandler 属性?

java - JPA:主键的重复条目

mysql - 锁定选择