public class ReadWriteLockTest {
public static void main(String[] args) {
final Queue3 q3 = new Queue3();
for(int i=0;i<3;i++)
{
new Thread(){
public void run(){
while(true){
q3.get();
}
}
}.start();
new Thread(){
public void run(){
while(true){
q3.put(new Random().nextInt(10000));
}
}
}.start();
}
}
}
class Queue3{
private Object data = null;//共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
ReadWriteLock rwl = new ReentrantReadWriteLock();
public void get(){
rwl.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " be ready to read data!");
Thread.sleep((long)(Math.random()*1000));
System.out.println(Thread.currentThread().getName() + "have read data :" + data);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
rwl.readLock().unlock();
}
}
public void put(Object data){
rwl.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " be ready to write data!");
Thread.sleep((long)(Math.random()*1000));
this.data = data;
System.out.println(Thread.currentThread().getName() + " have write data: " + data);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
rwl.writeLock().unlock();
}
}
}
线程ReadWriteLock 读写锁
原创
©著作权归作者所有:来自51CTO博客作者mb5fb94c9d4a0ba的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:用EL時,要設isELIgnored="false"
下一篇:PS 快捷键 总结
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
ReadWriteLock读写锁的使用
读写锁:写写、读写 是互斥的读读是不需要互斥的如下示例代码中,可以看到读的操
java 多线程 typescript shell webgl -
【JUC】004-ReadWriteLock读写锁
目录一、ReadWriteLock读写锁1、概述官方文档介绍:2、问题引出代码实现:运行结果:问题:3、使用读写锁代码实现:运行结果:4、
多线程 并发编程 java System 读写锁 -
并发编程--读写锁ReadWriteLock和ReentrantReadWriteLock(一)
Java并发编程包提供了读写锁的实现,其维护了一对相关的锁 — — “读取锁”和“写入WriteLock
ReentrantReadWriteLo ReadWriteLock 读锁 共享锁 java