我读到有关某些网页的锁,并试图有些网站所描述的基本情况运行。我是新线程使用,因此这是怎样的代码查找文件,读/写Lock实现在Java中
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)的implementaiton可运行的界面,
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)将试验CALSS
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自然应该读取锁定。但是这种情况并没有发生。是否有我缺少理解的东西?
你有问题吗? –
加我的问题..最后.. – user2626431