Java多线程对资源加锁同步无效是何原因?

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 ?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值