计算多个线程中的单个变量
我有以下可运行的课程。
public class OnesRun implements Runnable {
public int ones = 0;
private int passendNumber;
public OnesRun(int passendNumber) {
this.passendNumber = passendNumber;
}
public void run() {
if (passendNumber == 1)
ones++;
}
}
如果遇到 1,该类的每个实例都应该增加 ones
的值。
执行完所有线程后,我想从类外部读取 ones
的值。
- 如何增加
个
线程安全? - 我怎样才能访问 来自此类之外的
one
? 通过静态变量?或者我可以将其放入应用程序中吗 语境?
编辑:
我希望下面的伪代码能让我的意图更加清晰。
OnesRun.ones = getCurrentValueOnes();
while ( (number = readNumbersFromFile) != null) {
threadPool.execute(new OnesRun(number));
}
print("Overall values of ones " + OnesRun.ones);
I've got the following runnable class.
public class OnesRun implements Runnable {
public int ones = 0;
private int passendNumber;
public OnesRun(int passendNumber) {
this.passendNumber = passendNumber;
}
public void run() {
if (passendNumber == 1)
ones++;
}
}
Every instance of this class should increase the value of ones
if it encounters a one.
After all threads have been executed I want to read the value of ones
from outside the class.
- How can I increment
ones
thread-safe ? - How can I access
ones
from outside this class?
Through a static variable? Or can I put it into the application
context?
Edit:
I hope the following pseudo code makes my intentions more clear.
OnesRun.ones = getCurrentValueOnes();
while ( (number = readNumbersFromFile) != null) {
threadPool.execute(new OnesRun(number));
}
print("Overall values of ones " + OnesRun.ones);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
AtomicInteger
。您可以使用一个简单的吸气剂。或者我错过了什么?
更新
根据您的更新,以下是我将如何修改您的代码示例:
除了已经讨论过的内容(将
ones
设为private static AtomicInteger
并添加 getter/setter 对),我将两个成员都设置为final
,如果可能的话,这始终是可取的,尤其是在并发代码中。另请注意,
AtomicInteger
保留为实现细节 - 它不由类的公共接口公开。You can use an
AtomicInteger
.You may use a simple getter. Or am I missing something?
Update
Based on your update, here is how I would modify your code sample:
Apart from what's already been discussed (making
ones
aprivate static AtomicInteger
and adding a getter/setter pair), I made both membersfinal
, which is always advisable if possible, especially in concurrent code.Note also that
AtomicInteger
is kept as an implementation detail - it is not exposed by the public interface of the class.使用 AtomicInteger (线程安全)和静态属性。
Use AtomicInteger (thread-safe) and static property.