2014-05-12 07:10

题目链接

原题:

Write a thread safe data structure such that there could be only one writer at a time but there could be n readers reading the data. You can consider that incrementing or decrementing a variable is an atomic operation. If more than one threads try to write simultaneously then just select one randomly and let others wait

题目:写一个线程安全的数据结构,允许单线程写,n线程读。如果多个线程尝试写数据,随机选择一个,让其他线程等待。

解法:我用信号量试着写了一个,不过不太清楚“随机选择”这个要如何表示。

代码:

 // http://www.careercup.com/question?id=6751316000899072
import java.util.concurrent.Semaphore; public class FooBar {
public int n = 100;
private Semaphore sharedSemaphore;
private Semaphore exclusiveSemaphore; public FooBar(int n) {
// TODO Auto-generated constructor stub
this.n = n;
this.sharedSemaphore = new Semaphore(n);
this.exclusiveSemaphore = new Semaphore(1);
} public void reader() {
// The reader here is not to return a value, but to perform read()
// action. Thus it is 'void reader()'.
while (exclusiveSemaphore.availablePermits() < 1) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} try {
sharedSemaphore.acquire();
System.out.println("Performing read() operation.");
sharedSemaphore.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public void writer() {
while (exclusiveSemaphore.availablePermits() < 1
&& sharedSemaphore.availablePermits() < n) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} try {
exclusiveSemaphore.acquire();
System.out.println("Performing write() operation.");
exclusiveSemaphore.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public static void main(String[] args) {
FooBar fooBar = new FooBar(100); fooBar.reader();
fooBar.writer();
}
}

最新文章

  1. XMPP作为一个工具的意义
  2. 天气预报API(二):全球城市、景点代码列表(“旧编码”)
  3. 定时从多个Excel导入数据到SQL数据库
  4. MySQL源码分析以及目录结构 2
  5. Rserve, java调用R源文件
  6. 图片轮播(淡入淡出)--JS原生和jQuery实现
  7. HTML中的英文缩写标记、属性
  8. DHTMLX 前端框架 建立你的一个应用程序 教程(十)--保存表单中的数据
  9. Android4.0窗口机制和创建过程分析
  10. POJ 2975 Nim 尼姆博弈
  11. Linux编程之PING的实现
  12. EasyNVR-流媒体服务详解
  13. Entity Framework入门教程(3)---EF中的上下文简介
  14. 2017年java面试题库【归类篇】
  15. 简化开发:Lombok的使用
  16. Ubuntu18系统qt生成程序无法双击运行问题
  17. SpringBoot 使用Druid连接池
  18. [err]default argument given for parameter 3 of &#39;***&#39;
  19. LibreOJ #6002. 「网络流 24 题」最小路径覆盖
  20. 6、Docker图形化管理(Portainer)

热门文章

  1. vue+element-ui实现cookie登录
  2. javascript之常用正则表达式
  3. 从github克隆内容到本地时权限问题
  4. 使用CMake生成VS2010项目查看OpenCV源代码
  5. 解决windows7系统的快捷方式无法添加到任务栏
  6. .NET 前台调用后台事件和方法实现小结
  7. TP5.0:同一个控制器访问不同方法
  8. C#调用Python脚本并使用Python的第三方模块
  9. MYSQL短索引
  10. Android(java)学习笔记85:使用SQLite的基本流程