嗯,写一个读写锁,细节的东西挺多的
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 实现功能 只要有人在读就不能写,但可以读;有在写,则不能读也不能写
* 2011-10-14
*/
public class ReadWriteLock extends ReentrantLock {
Condition c = this.newCondition();
int readNum = 0;
public void readLock() throws InterruptedException {
this.lock();
readNum++;
System.out.println("read add one, now is " + readNum);
this.unlock();
}
public void readUnlock() throws InterruptedException {
//这里加锁,保证写不能在增加读人数的时候不能操作
this.lock();
if (readNum > 0)
readNum--;
if (readNum == 0 && this.hasWaiters(c)) {
c.signalAll();
}
System.out.println("read decrease one, now is " + readNum);
this.unlock();
}
public void writeLock() throws InterruptedException {
this.lock();
//如果有人在读,就把等待
while (readNum > 0) {
c.await();
}
System.out.println("now is writing...");
}
public void writeUnlock() {
System.out.println("ok write done");
this.unlock();
}
public static void main(String[] args) throws InterruptedException {
System.out.println("start!");
final ReadWriteLock lock = new ReadWriteLock();
Thread read1 = new Thread() {
@Override
public void run() {
try {
lock.readLock();
TimeUnit.SECONDS.sleep(3);
lock.readUnlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread read2 = new Thread() {
@Override
public void run() {
try {
lock.readLock();
TimeUnit.SECONDS.sleep(3);
lock.readUnlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread write1 = new Thread() {
@Override
public void run() {
try {
lock.writeLock();
TimeUnit.SECONDS.sleep(5);
lock.writeUnlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread write2 = new Thread() {
@Override
public void run() {
try {
lock.writeLock();
TimeUnit.SECONDS.sleep(5);
lock.writeUnlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread read3 = new Thread() {
@Override
public void run() {
try {
lock.readLock();
TimeUnit.SECONDS.sleep(3);
lock.readUnlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread read4 = new Thread() {
@Override
public void run() {
try {
lock.readLock();
TimeUnit.SECONDS.sleep(3);
lock.readUnlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
read1.start();
write1.start();
write2.start();
read2.start();
read3.start();
TimeUnit.SECONDS.sleep(3);
read4.start();
Thread.yield();
}
}