首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 企业软件 > 行业软件 >

java.util.concurrent详解(二)Se地图hore/FutureTask/Exchanger

2012-12-28 
java.util.concurrent详解(二)Semaphore/FutureTask/Exchanger-----------------------------------------

java.util.concurrent详解(二)Semaphore/FutureTask/Exchanger

-----------------------------------------
3. Semaphore
??? 我们先来学习一下JDK1.5 API中关于这个类的详细介绍:
“一个计数信号量。从概念上讲,信号量维护了一个许可集。如有必要,在许可可用前会阻塞每一个 acquire(),然后再获取该许可。每个 release() 添加一个许可,从而可能释放一个正在阻塞的获取者。但是,不使用实际的许可对象,Semaphore 只对可用许可的号码进行计数,并采取相应的行动。”

??? 我们一般用它来控制某个对象的线程访问对象

??? 例如,对于某个容器,我们规定,最多只能容纳n个线程同时操作
使用信号量来模拟实现

具体代码如下(参考 [JCIP])

?java.util.concurrent详解(二)Se地图hore/FutureTask/Exchangerjava.util.concurrent详解(二)Se地图hore/FutureTask/Exchanger
    ?java.util.concurrent详解(二)Se地图hore/FutureTask/Exchangerjava.util.concurrent详解(二)Se地图hore/FutureTask/Exchanger
      ?java.util.concurrent详解(二)Se地图hore/FutureTask/Exchangerjava.util.concurrent详解(二)Se地图hore/FutureTask/Exchanger
        import?java.util.ArrayList; ??import?java.util.concurrent.Exchanger; ????public?class?TestExchanger?{ ????????public?static?void?main(String[]?args)?{ ??????????final?Exchanger<ArrayList<Integer>>?exchanger?=?new?Exchanger<ArrayList<Integer>>(); ??????????final?ArrayList<Integer>?buff1?=?new?ArrayList<Integer>(10); ??????????final?ArrayList<Integer>?buff2?=?new?ArrayList<Integer>(10); ????????????new?Thread(new?Runnable()?{ ??????????????@Override??????????????public?void?run()?{ ??????????????????ArrayList<Integer>?buff?=?buff1; ??????????????????try?{ ??????????????????????while?(true)?{ ??????????????????????????if?(buff.size()?>=?10)?{ ??????????????????????????????buff?=?exchanger.exchange(buff);//开始跟另外一个线程交互数据??????????????????????????????System.out.println("exchange?buff1"); ??????????????????????????????buff.clear(); ??????????????????????????} ??????????????????????????buff.add((int)(Math.random()*100)); ??????????????????????????Thread.sleep((long)(Math.random()*1000)); ??????????????????????} ??????????????????}?catch?(InterruptedException?e)?{ ??????????????????????e.printStackTrace(); ??????????????????} ??????????????} ??????????}).start(); ?????????? ??????????new?Thread(new?Runnable(){ ??????????????@Override??????????????public?void?run()?{ ??????????????????ArrayList<Integer>?buff=buff2; ??????????????????while(true){ ??????????????????????try?{ ??????????????????????????for(Integer?i:buff){ ??????????????????????????????System.out.println(i); ??????????????????????????} ??????????????????????????Thread.sleep(1000); ??????????????????????????buff=exchanger.exchange(buff);//开始跟另外一个线程交换数据??????????????????????????System.out.println("exchange?buff2"); ??????????????????????}?catch?(InterruptedException?e)?{ ??????????????????????????e.printStackTrace(); ??????????????????????} ??????????????????} ??????????????}}).start(); ??????} ??}??



      ??? 总结:Exchanger在特定的使用场景比较有用(两个伙伴线程之间的数据交互)

热点排行