同步方法不是线程安全的

0 java multithreading synchronization

有人可以让我知道为什么下面的代码不是线程安全的?我得到的输出是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);
   }
 }
Run Code Online (Sandbox Code Playgroud)

Ale*_*dov 11

等待线程完成.加

threadA.join();
threadB.join();
Run Code Online (Sandbox Code Playgroud)

在打印结果之前.


Aja*_*rge 6

基本上,您在两个线程完成执行之前读取值.

您可以使用连接等待线程完成.

还尝试使用AtomicLongaddAndGet方法而不是同步的add方法.