在多个线程中计算单个变量 [英] Counting a single variable in multiple threads

查看:61
本文介绍了在多个线程中计算单个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下可运行的类.

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的值.

Every instance of this class should increase the value of ones if it encounters a one.

在执行完所有线程后,我想从类外部读取 ones 的值.

After all threads have been executed I want to read the value of ones from outside the class.

  1. 如何增加ones线程安全?
  2. 我如何访问ones 来自这个班级之外?通过静态变量?或者我可以把它放到应用程序中上下文?
  1. How can I increment ones thread-safe ?
  2. How can I access ones from outside this class? Through a static variable? Or can I put it into the application context?

<小时>

我希望下面的伪代码能让我的意图更清晰.

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);

推荐答案

如何增加线程安全的值?

How can I increment ones thread-safe ?

您可以使用 AtomicInteger.

You can use an AtomicInteger.

我怎样才能从这个班级之外访问那些?通过静态变量?或者我可以把它放到应用程序上下文中吗?

How can I access ones from outside this class? Through a static variable? Or can I put it into the application context?

你可以使用一个简单的 getter.还是我遗漏了什么?

You may use a simple getter. Or am I missing something?

根据您的更新,我将如何修改您的代码示例:

Based on your update, here is how I would modify your code sample:

public class OnesRun implements Runnable {

    private static final AtomicInteger ones = new AtomicInteger();

    private final int passendNumber;

    public OnesRun(int passendNumber) {
        this.passendNumber = passendNumber;
    }

    public void run() {
        if (passendNumber == 1)
            OnesRun.ones.incrementAndGet();
    }

    public static void setOnes(int newValue) {
        ones.set(newValue);
    }

    public static int getOnes() {
        return ones.get()
    }
}

...

OnesRun.setOnes(getCurrentValueOnes());

while ( (number = readNumbersFromFile) != null) {
   threadPool.execute(new OnesRun(number));
}

print("Overall values of ones " + OnesRun.getOnes());

除了已经讨论过的内容(使 ones 成为 private static AtomicInteger 并添加一个 getter/setter 对),我将两个成员都设为 final,如果可能的话,这总是可取的,尤其是在并发代码中.

Apart from what's already been discussed (making ones a private static AtomicInteger and adding a getter/setter pair), I made both members final, which is always advisable if possible, especially in concurrent code.

另请注意,AtomicInteger 被保留为实现细节 - 它不会被类的公共接口公开.

Note also that AtomicInteger is kept as an implementation detail - it is not exposed by the public interface of the class.

这篇关于在多个线程中计算单个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆