首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

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

2012-08-26 
Java多线程对资源加锁同步无效是何原因?public class IncrementAndDecrement {private static Integer bal

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 ?

热点排行