【发布时间】:2018-09-20 05:28:28
【问题描述】:
当我想使用同步关键字或锁进行更新时,它在 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
}
}
}
【问题讨论】:
-
Lock lock = new ReentrantLock();你正在为每个线程创建一个新对象 -
对于这个用例,我建议使用
AtomicInteger和getAndIncrement或incrementAndGet。那么你就不再需要锁了。 -
您的
sum的增量将更容易(并且等效地)写为sum++;(除了您有时会使用缓存的 Integer 实例)。自动装箱“免费”完成您在此处所做的工作。
标签: java multithreading synchronization