线程同步问题(更新变量和)

时间:2018-09-20 05:28:29

标签: java multithreading synchronization

当我想使用同步关键字或锁更新时,当sum变量为int而不是Integer对象时,它可以工作。

代码看起来像这样-

public class TestSynchronized {
  private  Integer sum = new Integer(0);

  public static void main(String[] args) {
    TestSynchronized test = new TestSynchronized();
    System.out.println("The sum is :" + test.sum);
  }

  public TestSynchronized() {
    ExecutorService executor = Executors.newFixedThreadPool(1000);

    for (int i = 0; i <=2000; i++) {
      executor.execute(new SumTask());
    }

    executor.shutdown();

    while(!executor.isTerminated()) {
    }
  }

  class SumTask implements Runnable {
    Lock lock = new ReentrantLock();

    public void run() {
    lock.lock();

      int value = sum.intValue() + 1;
      sum = new Integer(value);

        lock.unlock(); // Release the lock
      }

  }
}

1 个答案:

答案 0 :(得分:2)

问题在于,您为每个locks对象分别设置了SumTask。这些对象应该共享locks

使用lock方法创建一个TestSynchronized()对象。这应该由所有new SumTask(lock)对象共享。

所以您的SumTask类如下:

class SumTask implements Runnable {
    Lock lock;

    public SumTask(Lock commonLock) {
        this.lock = commonLock;
    }

    public void run() {
        lock.lock();

        int value = sum.intValue() + 1;
        sum = new Integer(value);

        lock.unlock(); // Release the lock
    }

}

别忘了用commonLock方法创建一个TestSynchronized()对象:

  Lock lock = new ReentrantLock();

  executor.execute(new SumTask(commonLock));