我可以在运行方法中保留 Java 线程的计数器吗?



我有一个类变量,总和。每次我启动一个新线程时,我都希望总和增加。似乎 run 只被调用一次,我找不到更好的信息来告诉我更多关于它的信息。有没有办法用锁来实现这一点?下面是一些简单的代码:

public class MyClass implements Runnable{
    static int sum = 0;
    public static void main(String[] args) throws InterruptedException {
        for(int i = 0; i < 5; ++i){
            Thread t = new Thread(new MyClass());
            t.start();
            t = null;
        }
    }
    @Override
        public synchronized void run() {
        ++sum;
        System.out.println(sum);
    }
}

静态变量中保持可变状态是一种不好的做法,但这是您解决此问题的方法:

public class MyClass implements Runnable {
    static AtomicInteger counter = new AtomicInteger(0);
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; ++i) {
            Thread t = new Thread(new MyClass());
            t.start();
            t = null;
        }
    }
    @Override
    public void run() {
        int sum = counter.incrementAndGet();
        System.out.println(sum);
    }
}

由于 sum 是实例变量,例如 MyClass 有一个变量sum,其初始值为 0 。将Sum标记为静态,以便在类级别使用它。

public class MyClass implements Runnable{
    static int sum = 0;
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; ++i) {
            Thread t = new Thread(new MyClass());
            t.start();
            t = null;
        }
    }
    public void run() {
      synchronized (this) {
        sum++;
       System.out.println(sum);
   }
 }
}

这是输出:

1
2
3
4
5

最新更新