gpt4 book ai didi

java - Java 中的临时线程限制示例

转载 作者:搜寻专家 更新时间:2023-10-30 21:28:36 24 4
gpt4 key购买 nike

我正在阅读《Java 并发实践》这本书。作者没有提供任何临时线程限制的例子,只是说它“描述了何时维护线程限制的责任完全落在实现上”。

谁能举个例子?我无法理解它与堆栈限制、ThreadLocal 等的区别。

谢谢。

最佳答案

我在理解有关临时线程限制的文本时也遇到了问题。但是在https://www.cs.umd.edu/class/spring2013/cmsc433/Notes/10-CMSC433-Confinement.pdf的帮助下我认为这意味着:

最特别的线程配置方式是简单地用通俗易懂的语言(如英语)向其他程序员说明/记录他们不应访问特定对象。

PDF 链接提到:

You could decide on a set of conventions to restrict the use of shared state and then work to have all the code follow them. You agree on an order of who gets to do what and when that ensures locks aren’t needed. If you manage it, that’s great. However, you are using 100% human-level protection rather than anything language-level, which can be difficult. Part of an ad-hoc agreement could be that you share state in a very specific way; everything that’s shared is marked as volatile and for each shared object, only one thread is ever allowed to be able to write to it. In a single-writer, multiple-reader scenario, you don’t need synchronization if the variable is volatile. Very fragile and very subtle!

所以一个例子可以像记录这样的东西一样简单:

// Don't use this object in other threads than Thread X
private SomeType someObject;
public SomeType getSomeObject() { return someObject; }

// Don't modify this from any other thread than Thread X.
// So use it read-only for those other threads.
private volatile int someNumber;

虽然书中正文:

describes when the responsibility for maintaining thread confinement falls entirely on the implementation

在这种情况下确实使“实现”一词有些不清楚。这个词暗示了代码,但是恕我直言,使用“文档”这个词或客户端实现/共享数据的使用会更清楚。

关于java - Java 中的临时线程限制示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9039503/

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