读读之间不互斥,但读写之间,写写之间互斥。提高了效率保证了安全。
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class MyQueue
{
// 共享数据。该数据只能被一个线程写,可以被多个线程同时读
private Object data;
// 读读之间不互斥,但读写之间,写写之间互斥
ReadWriteLock rwlock = new ReentrantReadWriteLock();
// 取数据
public void get()
{
rwlock.readLock().lock();
try
{
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ":准备读取数据了");
System.out.println(threadName + ":读取的数据是" + data);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
rwlock.readLock().unlock();
}
}
// 写数据
public void put(Object data)
{
rwlock.writeLock().lock();
try
{
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ":准备写数据了");
this.data = data;
System.out.println(threadName + ":写的数据是" + data);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
rwlock.writeLock().unlock();
}
}
}
import java.util.Random;
public class MyQueueTest
{
public static void main(String[] args)
{
final MyQueue myqueue = new MyQueue();
for (int i = 0; i < 100; i++)
{
new Thread(new Runnable() {
public void run()
{
myqueue.get();
}
}).start();
new Thread(new Runnable() {
public void run()
{
myqueue.put(new Random().nextInt(1000));
}
}).start();
}
}
}
相关文章
- 04-0311.深入理解读写锁ReentrantReadWriteLock
- 04-03红米4A全版本通刷|2016111 2016112|官方售后纯净线刷包|刷机解锁救砖|可解账户锁
- 04-03JUC基础(21):ReentrantReadWriteLock读写锁
- 04-03ReentrantReadWriteLock读写锁的使用
- 04-03深入理解java:2.3.2. 并发编程concurrent包 之重入锁/读写锁/条件锁
- 04-03[源码分析]读写锁ReentrantReadWriteLock
- 04-03018-并发编程-java.util.concurrent.locks之-ReentrantReadWriteLock可重入读写锁
- 04-03读写锁ReentrantReadWriteLock的使用
- 04-03JUC——线程同步锁(ReentrantReadWriteLock读写锁)
- 04-03java读写锁源码分析(ReentrantReadWriteLock)