我正在阅读一些网页中的锁,并尝试运行某个网站描述的基本案例。我是线程使用的新手,所以这就是代码查找文件的方式,
1)读写锁功能(不可重入,非常基础)
public ReadWriteLock() {
// TODO Auto-generated constructor stub
}
synchronized void readLock(String name) throws InterruptedException {
//tname = threadName;
if(writers>0 || writereq>0){
wait();
}
readers++;
System.out.println(name + " locks for reading resource....");
}
synchronized void readUnLock(String name) throws InterruptedException{
//tname = threadName;
readers--;
System.out.println(name + "unlocks reading resource....");
notifyAll();
}
synchronized void writeLock(String name) throws InterruptedException{
//tname = threadName;
writereq++;
if(writers>0 || readers>0){
System.out.println( name + " waits for writing...");
wait();
}
writereq--;
writers++;
System.out.println(" locks for writing resource....");
}
synchronized void writeUnLock(String name) throws InterruptedException{
//tname = threadName;
writers--;
System.out.println(name + " unlocks for writing resource....");
notifyAll();
}
2)Runnable接口的实现,
public class Runner implements Runnable{
private ReadWriteLock rwl;
private String name;
public Runner(ReadWriteLock rwl, String name) {
// TODO Auto-generated constructor stub
this.rwl=rwl;
this.name = name;
}
void runlocks(int method){
//String name = Thread.currentThread().getName();
switch(method){
case 1:
try {
rwl.readLock(name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}break;
case 2:
try {
rwl.readUnLock(name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} break;
case 3:
try {
rwl.writeLock(name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} break;
case 4:
try {
rwl.writeUnLock(name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} break;
}
}
@Override
public void run() {
//String name = Thread.currentThread().getName();
// TODO Auto-generated method stub
//System.out.println("Thread started "+ name);
//int method = 1;
// TODO Auto-generated method stub
//System.out.println(this.threadName + " has started!");
}
3) 测试课
public class TestClass {
public static void main(String[] args) throws InterruptedException {
ReadWriteLock rwl = new ReadWriteLock();
Runner r1 =new Runner(rwl,"Thread1");
Thread t1 = new Thread(r1);
t1.setName("Thread1");
Runner r2 =new Runner(rwl,"Thread2");
Thread t2 = new Thread(r2);
t2.setName("Thread2");
t1.start();
t2.start();
r1.runlocks(1); //r1 locks to read
r2.runlocks(1); //r2 locks to read
r1.runlocks(2); //r1 unlocks read
r2.runlocks(2); //r1 unlocks read
r1.runlocks(3); //r1 locks to write
r2.runlocks(1); //r2 tries to lock for read but waits.. and the code gets struck here
r1.runlocks(4); //r1 releases lock of write
}
}
我的问题是.. 在测试器类中,线程 1 获得写入锁,然后线程 2 尝试读取但它不能等待.. 此时应该执行线程 1 解锁写入锁的下一条语句,线程 2 应该自然会读到锁。但是这种情况不会发生。有什么我想不明白的吗?