Semaphore信号量分为一元和多元 一元可以作为互斥的信号灯,多元可以限制线程同时(同步方式)执行的个数。 1.多元信号量 public class SemphoretwoDemo { public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); SemphoretwoDemo t = new SemphoretwoDemo(); final BoundedHashSet<String> set = t.getSet(); for (int i = 0; i < 3; i++) {//三个线程同时操作add exec.execute(new Runnable() { public void run() { try { set.add(Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } } }); } for (int j = 0; j < 3; j++) {//三个线程同时操作remove exec.execute(new Runnable() { public void run() { set.remove(Thread.currentThread().getName()); } }); } exec.shutdown(); } public BoundedHashSet<String> getSet() { return new BoundedHashSet<String>(2);//定义一个边界约束为2的线程 } class BoundedHashSet<T> { private final Set<T> set; private final Semaphore semaphore; public BoundedHashSet(int bound) { this.set = Collections.synchronizedSet(new HashSet<T>()); this.semaphore = new Semaphore(bound, true); } public void add(T o) throws InterruptedException { semaphore.acquire();//信号量控制可访问的线程数目 set.add(o); System.out.printf("add:%s%n",o); } public void remove(T o) { if (set.remove(o)) semaphore.release();//释放掉信号量 System.out.printf("remove:%s%n",o); } } } 2.一元信号量 /** *仓库(我觉得pingyin好理解一些) */ public class CangKu { private Semaphore sema=new Semaphore(1); private boolean isFull=false; public void put() { try { if(!this.isFull) { //申请许可 sema.acquire(); System.out.println("商品放满的,可以来取的"); isFull=!isFull; //释放资源 sema.release(); } } catch (InterruptedException e) { e.printStackTrace(); } } public void get() { try { if(this.isFull) { //申请许可 sema.acquire(); System.out.println("商品我取走的,可以来放的"); isFull=!isFull; //释放资源 sema.release(); } } catch (InterruptedException e) { e.printStackTrace(); } } } //get public class GetThread extends Thread{ private CangKu cu; public GetThread(CangKu cu) { this.cu = cu; this.start(); } public void run() { while(true) { this.cu.get(); } } } //put public class PutThread implements Runnable { private CangKu cu; public PutThread(CangKu cu) { this.cu = cu; new Thread(this).start(); } public void run() { while(true) { this.cu.put(); } } } public class CangKUMain { /** * 用信号量测试 */ public static void main(String[] args) { CangKu cu=new CangKu(); PutThread pth=new PutThread(cu); GetThread gth=new GetThread(cu); } } |
行业聚焦 面试交流 职位推荐 开发视频 技术交流 腾讯微博 新浪微博
友情链接:课课家教育 阿里云 鲜果 W3Cfuns前端网 中国企业家 环球企业家 投资界 传媒梦工场 MSN中文网 Android开发者社区 cnbeta 投资中国网 又拍云存储 美通说传播 IT茶馆 网商在线 商业评论网 TechOrange IT时代周刊 3W创新传媒 开源中国社区 二维工坊 Iconfans 推酷 智能电视网 FreeBuf黑客与极客 财经网 DoNews 凤凰财经 新财富 eoe移动开发者社区 i黑马 网易科技 新浪科技 搜狐IT 创业家 创业邦 腾讯财经 福布斯中文网 天下网商 TechWeb 雷锋网 新浪创业 和讯科技 品途O2O 极客公园 艾瑞网 抽屉新热榜 卖家网 人民网通信频道 拉勾网 创新派 简单云主机
手机版|黑名单|守望者 成才网 在线教育 linux 高级程序设计 C/C++ 大数据
( 蜀ICP备14029946号 )
成都守望者科技有限公司 © 2013-2016 All Rights Reserved