增加一个计数器,使用两个线程。

huangapple go评论71阅读模式
英文:

Increase a Counter using 2 threads

问题

我试图通过使用2个线程将初始为0的计数器增加到1000。以下是我的代码:

class CounterVar {
  private int val;

  CounterVar() {
    val = 0;
  }

  public void increment() {
    Object obj = new Object();
    synchronized(obj) {
      val++;
    }
  }

  public int getVal() {
    return val;
  }
}

public class Counter {
  public static void main(String[] args) throws InterruptedException {
    CounterVar counter = new CounterVar();
    Thread t1 = new Thread(() -> {
      for (int i = 0; i < 500; i++)
        counter.increment();
    });
    Thread t2 = new Thread(() -> {
      for (int i = 0; i < 500; i++)
        counter.increment();
    });
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    System.out.println(counter.getVal());
  }
}

我在这里无法获得输出为1000,它总是小于1000。我已经实现了同步,但不明白问题出在哪里。同时,我想澄清一下,当线程1增加计数器时,是否会让线程2陷入饥饿状态。提前谢谢。

英文:

I am trying to increase a counter which is initially 0,
to 1000 using 2 threads. Here is my code

class CounterVar {
  private int val;

  CounterVar() {
    val = 0;
  }

  public void increment() {
    Object obj = new Object();
    synchronized(obj) {
      val++;
    }
  }

  public int getVal() {
    return val;
  }
}

public class Counter {
  public static void main(String[] args) throws InterruptedException {
    CounterVar counter = new CounterVar();
    Thread t1 = new Thread(() - &gt; {
      for (int i = 0; i &lt; 500; i++)
        counter.increment();
    });
    Thread t2 = new Thread(() - &gt; {
      for (int i = 0; i &lt; 500; i++)
        counter.increment();
    });
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    System.out.println(counter.getVal());
  }
}

I am not getting output as 1000 here, its always less. I have implemented synchronization and dont understand what is wrong here.
Also wanted to clarify if I am starving thread2 while thread1 is incrementing the counter.

Thanks in Advance.

答案1

得分: 8

你没有正确同步线程。要同步多个线程,必须使用一个共同的对象作为同步机制,但你为每个线程创建了一个新对象。尝试这样做:

class CounterVar {
  private int val;
  private final Object obj = new Object();

  public void increment() {
    synchronized(obj) {
      val++;
    }
  }
}

或者,更简单地去掉 obj

public synchronized void increment() {
  ...
}
英文:

You are not synchronizing the threads correctly. To synchronize multiple threads, you have to use a common object as the synchronization mechanism, but you are creating a new object for each thread. Instead, try this:

class CounterVar {
  private int val;
  private final Object obj = new Object();

  public void increment() {
    synchronized(obj) {
      val++;
    }
  }

Or, simpler without the obj:

public synchronized void increment() {
  ...
}

huangapple
  • 本文由 发表于 2020年10月19日 11:45:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64420896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定