1. 概述
本文将介绍如何在Java中使用synchronized块。
简单地说,在多线程环境中,当两个或多个线程试图同时更新可变的共享数据时,就会出现竞争冒险(race condition)。Java提供了一种机制,通过同步线程对共享数据的访问来避免竞争冒险。
标记为synchronized的逻辑段成为synchronized块,在任何给定时间只允许一个线程执行该synchronized块。
2. 为什么需要同步?
让我们考虑一个典型的竞争冒险,当我们计算总和时,多个线程执行calculate()方法:
public class BaeldungSynchronizedMethods {
private int sum = 0;
public void calculate() {
setSum(getSum() + 1);
}
// standard setters and getters
}
让我们写一个简单的测试:
@Test
public void givenMultiThread_whenNonSyncMethod() {
ExecutorService service = Executors.newFixedThreadPool(3);
BaeldungSynchronizedMethods summation = new BaeldungSynchronizedMethods();
IntStream.range(0, 1000)
.forEach(count -> service.submit(summation::calculate));
service.awaitTermination(1000, TimeUnit.MILLISECONDS);
assertEquals(1000, summation.getSu