gpt4 book ai didi

java - 同步方法不是线程安全的

转载 作者:行者123 更新时间:2023-12-01 06:26:21 24 4
gpt4 key购买 nike

有人可以告诉我为什么下面的代码不是线程安全的吗?我得到的输出是 0 或 45 或 90。共享资源计数器有一个同步方法,所以我一直期望 90 作为输出。我在这里错过了什么吗?请指教。请让我知道如何使这段代码线程安全。

class Counter{

long count = 0;

public synchronized void add(long value){
this.count += value;
}
}
class CounterThread extends Thread{

protected Counter counter = null;

public CounterThread(Counter counter){
this.counter = counter;
}

public void run() {
for(int i=0; i<10; i++){
counter.add(i);
}
}
}
public class Example {

public static void main(String[] args){

Counter counter = new Counter();
Thread threadA = new CounterThread(counter);
Thread threadB = new CounterThread(counter);

threadA.start();
threadB.start();

System.out.println(counter.count);
}
}

最佳答案

等待线程完成。添加

threadA.join();
threadB.join();

在打印结果之前。

关于java - 同步方法不是线程安全的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12154003/

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