Java中 synchronized 关键字用来同步多个线程对同一个代码块的访问。对于类中被 synchronized 修饰过的多个普通成员方法,对于同一个对象,同一时刻只能有一个方法被执行,如果有多个线程,则其他线程需要等待。通过如下的例子来说明。
public class Test { private static int counter = 0; public synchronized void increase() { counter += 1; } public synchronized void decrease() { counter -= 1; } public static void main(String []args) throws InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(4); Test test = new Test(); IncreaseThread increaseThread = new IncreaseThread(test); DecreaseThread decreaseThread = new DecreaseThread(test); executorService.submit(increaseThread); executorService.submit(decreaseThread); executorService.shutdown(); System.out.println(counter); } }
其中 IncreaseThread 和 DecreaseThread 是实现了 Runnable 接口的两个线程,分别调用 increase 和 decrease 两个方法各100000次,来对 counter 进行操作。
如果 increase 和 decrease 两个方法不加 synchronized 关键字进行修饰,由于 += 和 -= 不是原子操作,会出现运行结果不可预测的情况,可能会是0,也可能会是-1,2,1等;如果加上 synchronized 关键字,increase 和 decrease 两个方法不可能同时对 counter 进行操作,所以运行结果总是 0。