您的位置:首页 > 职场人生

Careercup - Microsoft面试题 - 6751316000899072

2014-05-12 07:14 253 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: