gpt4 book ai didi

java - 我可以在 run 方法中保留 Java 线程的计数器吗?

转载 作者:行者123 更新时间:2023-12-02 04:43:56 26 4
gpt4 key购买 nike

我有一个类变量 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/

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