共享资源的简单示例
来源:互联网 发布:淘宝货到付款订单快递 编辑:程序博客网 时间:2024/06/06 04:21
/** * 资源共享的示例 * 装饰性花园仿真程序 * 花园委员会希望知道每天通过多个大门进入公园的总人数 * 每个大门都有一个十字专转门或某种形式的计数器, * 并且任何一个十字转门的计数值递增时, * 就表示公园的总人数的共享计数值也会递增 * * @author cxp * @data 2016-08-29 * @modify * */class Count { private int count = 0; private Random rand = new Random(47);// 47为随机数生成器的种子,默认将当前时间作为随机数的种子 // 移除synchronized关键字,程序将会失败 public synchronized int increment() { int temp = count; if (rand.nextBoolean())// 把count读取到temp中到递增temp并将其存储回count的这段时间里,大约一半的时间产生让步 Thread.yield(); return (count = ++temp); } public synchronized int value() { return count; }}class Entrance implements Runnable { private static Count count = new Count(); private static List<Entrance> entrances = new ArrayList<Entrance>(); private int number = 0; // 不需要同步对其的访问 private final int id; private static volatile boolean canceled = false; // 在volatile域里是原子操作 public static void cancel() { canceled = true; } public Entrance(int id) { this.id = id; entrances.add(this); } @Override public void run() { while (!canceled) { synchronized (this) { number++; } print(this + " Total:" + count.increment()); try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { print("sleep interrupted"); } } print("Stopping" + this); } public synchronized int getValue() { return number; } @Override public String toString() { return "Entrance " + id + ": " + getValue(); } public static int getTotalCount() { return count.value(); } public static int sumEntrances() { int sum = 0; for (Entrance entrance : entrances) sum += entrance.getValue(); return sum; }}public class OrnamentalGarden { public static void main(String[] args) throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); for (int i = 0; i < 5; i++) exec.execute(new Entrance(i)); // 运行一段时间,然后停止和收集数据 TimeUnit.SECONDS.sleep(3);// 当前线程睡眠3秒 Entrance.cancel();// 发送cancel()消息 exec.shutdown(); if (!exec.awaitTermination(250, TimeUnit.MILLISECONDS))//等待每个任务结束,在超时时间达到之前全部结束返回true,否则返回false print("Some task were not terminated"); print("Total:" + Entrance.getTotalCount()); print("Sum of Entrances:" + Entrance.sumEntrances()); }}
0 0
- 共享资源的简单示例
- 谢谢 共享资源的朋友
- 一款共享资源的软件
- 共享资源的公平性研究
- 线程共享资源的问题
- 我的共享资源
- 共享资源
- 共享资源
- 共享资源
- 多线程的共享资源的解决方案
- SetMenu的简单示例
- 简单的CodeDOM示例
- gridview的简单示例
- 简单的iBatisNet示例
- hook的简单示例
- 简单的多线程示例
- 简单的Ajax示例
- JMX的简单示例
- 【codevs】1506 传话 Tarjan
- Spring学习笔记(二)后处理器与AOP
- javascript 表达式和运算符 对象和数组的初始化表达式 十八
- TMS320C6678外部存储器DDR3硬件设计以及软件调试
- tcp4次挥手
- 共享资源的简单示例
- 百度地图API使用
- 菜鸟商城Android完整源码分享
- Struts2 入门(二) 之 配置文件中的 Action 元素
- MFC属性对话框
- linux中ctrl+z和ctrl+c的区别
- hihocoder #1043 : 完全背包
- swift中UIBarButtonItem颜色不正确显示解决办法
- LightOJ 1094 Farthest Nodes in a Tree 树的直径