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