Careercup - Microsoft面试题 - 6751316000899072
2014-05-12 07:14
253 查看
2014-05-12 07:10
题目链接
原题:
题目:写一个线程安全的数据结构,允许单线程写,n线程读。如果多个线程尝试写数据,随机选择一个,让其他线程等待。
解法:我用信号量试着写了一个,不过不太清楚“随机选择”这个要如何表示。
代码:
题目链接
原题:
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(); } }
相关文章推荐
- Careercup - Microsoft面试题 - 5684901156225024
- Careercup - Microsoft面试题 - 5204967652589568
- Careercup - Microsoft面试题 - 6337018766295040
- Careercup - Microsoft面试题 - 6543214668414976
- Careercup - Microsoft面试题 - 5700293077499904
- Careercup - Microsoft面试题 - 5680049562845184
- Careercup - Microsoft面试题 - 5428361417457664
- Careercup - Microsoft面试题 - 5188169901277184
- Careercup - Microsoft面试题 - 4840369632051200
- Careercup - Microsoft面试题 - 6282862240202752
- Careercup - Microsoft面试题 - 5485521224597504
- Careercup - Microsoft面试题 - 5173689888800768
- Careercup - Microsoft面试题 - 5672369481842688
- Careercup - Microsoft面试题 - 6314866323226624
- Careercup - Microsoft面试题 - 5718181884723200
- Careercup - Microsoft面试题 - 5917873302142976
- Careercup - Microsoft面试题 - 5799446021406720
- Careercup - Microsoft面试题 - 5752271719628800
- Careercup - Microsoft面试题 - 24313662
- Careercup - Microsoft面试题 - 24308662