讀讀之間不互斥,但讀寫之間,寫寫之間互斥。提升了效率保證了安全。
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();
}
}
}java