* 读写线程: 3个读线程,2个写线程
* 规则:读读并发,读写互斥,写写互斥,写优于读
* ReadWriteLock
*/
@Test
public void testReaderWriter() {
final ReadWriteLock lock = new ReadWriteLock();
Runnable reader = new Runnable() {
public void run() {
lock.readLock();
try { Thread.sleep(1*1000); }catch(Exception e){}
System.out.println(Thread.currentThread().getName()+" ************ running");
try { Thread.sleep(3*1000); }catch(Exception e){}
lock.readUnLock();
}
};
Runnable writer = new Runnable() {
public void run() {
lock.writeLock();
System.out.println(Thread.currentThread().getName()+" **************************** running");
try { Thread.sleep(5*1000); }catch(Exception e){}
lock.writeUnLock();
}
};
Thread r1 = new Thread(reader, "read thread 1");
Thread r2 = new Thread(reader, "read thread 2");
Thread r3 = new Thread(reader, "read thread 3");
Thread w1 = new Thread(writer, "write thread 1");
Thread w2 = new Thread(writer, "write thread 2");
w1.start();w2.start();
r1.start();r2.start();r3.start();
try {
r1.join();r2.join();r3.join();
w1.join();w2.join();
}catch(Exception e) {
}
}
public static class ReadWriteLock {
private int readCount = 0; //正在读的线程数量
private int writeCount = 0; //正在写的线程数量
private int waitWriteCount = 0; //等待写的线程数量
//private boolean isWriteFirst = true; //写优于读
//当有写线程,或者写线程的等待数量不为0时, 读线程阻塞;非阻塞时,读线程数量加一
public synchronized void readLock() {
while ( writeCount>0 || waitWriteCount>0 ) {
try {
wait();
}catch(Exception e) {
}
}
readCount++;
}
//当读线程完成操作时,读线程数量减一,并通知
public synchronized void readUnLock() {
readCount--;
notifyAll();
}
//使当前等待线程数量加一;当读线程数量非空,或者写线程数量非空时,阻塞此线程; 唤醒此线程后使得当前等待线程数量减一,同时使得当前写线程数量加一
public synchronized void writeLock() {
waitWriteCount++;
while ( readCount>0 || writeCount>0 ) {
try {
wait();
}catch(Exception e) {}
}
waitWriteCount--;
writeCount++;
}
//使得当前写线程数量减一,并发送通知
public synchronized void writeUnLock() {
writeCount--;
notifyAll();
}
}