---
title: "Java多线程对资源加锁同步无效是何原因？"
author: "Will_Turner"
date: "2012-03-01T22:18:16Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-03-01T22:18:16Z"
id: 1434803
url: "https://will-turner.iteye.com/blog/1434803"
---

```
public class IncrementAndDecrement {
	private static Integer balance=0;//引起竞争的资源
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ExecutorService executor=Executors.newCachedThreadPool();
		executor.execute(new IncrementTask());
		executor.execute(new DecrementTask());
		executor.execute(new DecrementTask());
		executor.execute(new IncrementTask());

		executor.shutdown();
		while(!executor.isTerminated()){
			
		}
		
		System.out.println("balance="+balance);
	}
	
	/**
	 * 递增操作任务
	 * @author Administrator
	 *
	 */
	private static class IncrementTask implements Runnable{
		public void run(){
			synchronized(balance){
				int newBalance=balance+1;
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				balance=newBalance;
			}
		}
	}
	
	/**
	 * 递减操作任务
	 */
	private static class DecrementTask implements Runnable{
		public void run(){
			synchronized(balance){
				int newBalance=balance-1;
				try {
					Thread.sleep(3);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				balance=newBalance;
			}
		}
	}

}
```

 程序想实现的效果是，对共享的资源（Integer类型的balance）进行增加和减少的操作，增加和减少分别通过两个线程任务来执行。在两个线程任务类中，在进行增或者减的时候都是用了synchronized关键字对资源（balance）加锁。但是执行的结果是并没有实现同步。我很疑惑，不知道什么原因。并且假如我将增减操作封装到方法当中，并且这些方法是用synchronized描述，那么执行的结果是同步的。Y ？