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

当我想使用 synchronized 关键字或锁进行更新时,它在 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

      }


  }

}


素胚勾勒不出你
浏览 142回答 1
1回答

四季花海

问题是您已将locks每个SumTask对象分开。这些对象应该共享locks。lock在TestSynchronized()方法中创建一次对象。这应该由所有new SumTask(lock)对象共享。所以你的SumTask班级看起来像:class SumTask implements Runnable {&nbsp; &nbsp; Lock lock;&nbsp; &nbsp; public SumTask(Lock commonLock) {&nbsp; &nbsp; &nbsp; &nbsp; this.lock = commonLock;&nbsp; &nbsp; }&nbsp; &nbsp; public void run() {&nbsp; &nbsp; &nbsp; &nbsp; lock.lock();&nbsp; &nbsp; &nbsp; &nbsp; int value = sum.intValue() + 1;&nbsp; &nbsp; &nbsp; &nbsp; sum = new Integer(value);&nbsp; &nbsp; &nbsp; &nbsp; lock.unlock(); // Release the lock&nbsp; &nbsp; }}并且不要忘记commonLock在TestSynchronized()方法中创建一个对象:&nbsp; Lock lock = new ReentrantLock();&nbsp; executor.execute(new SumTask(commonLock));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java