读读之间不互斥,但读写之间,写写之间互斥。提高了效率保证了安全。
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();
}
}
}
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();
}
}
}