我有一个类变量 sum。每次我启动一个新线程时,我都希望总和增加。看来 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);
}
}
关于java - 我可以在 run 方法中保留 Java 线程的计数器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29857692/