一道多线程面试题

zhouixi 2019-04-13 12:04:48

面试官问:


10个线程同时读是不会互斥的。
如果让其中一个线程写,其他线程读。怎么写。
就是说其中一个线程拿到写锁,其余剩下的线程只能读,不能写。






public class ThreadWriter {

static CyclicBarrier cyclicBarrier = new CyclicBarrier(10);
private static ReadWriteLock lock = new ReentrantReadWriteLock();
private static int number = 0;

public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Thread() {
@Override
public void run() {
try {
System.err.println("线程" + Thread.currentThread().getName() + "到达!!!");
cyclicBarrier.await();
if (lock.writeLock().tryLock()) {
try {
Thread.sleep(10);
number++;
System.out.println(Thread.currentThread().getName() + "-------正在写-------");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
} else {
lock.readLock().lock();
System.out.println(Thread.currentThread().getName() + "-------正在读-------");
lock.readLock().unlock();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}







请问 这样模拟是对的吗。
...全文
37 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧