这是我试图演示嵌套锁问题的代码,
import java.util.concurrent.locks.*;
class SharedResource{
private static final Lock lock = new ReentrantLock();
private void methodThree(String name,int x) throws Exception{
lock.lock();
while(x <= 15){
System.out.println("METHOD-THREE / THREAD-NAME : "+name+" NUM-VAL "+x);
x++;
Thread.sleep(250);
}
}
private void methodTwo(String name,int x) throws Exception{
lock.lock();
while(x <= 10){
System.out.println("METHOD-TWO / THREAD-NAME : "+name+" NUM-VAL "+x);
x++;
Thread.sleep(250);
}
methodThree(name,x);
}
public void methodOne(String name,int x) throws Exception{
try{
lock.lock();
while(x <= 5){
System.out.println("METHOD-ONE / THREAD-NAME : "+name+" NUM-VAL "+x);
x++;
Thread.sleep(250);
}
methodTwo(name,x);
}finally{
lock.unlock();
}
}
}
class MyRequestREQ extends Thread{
private SharedResource res;
private int num = 1;
MyRequestREQ(SharedResource res,String name){
super(name);
this.res = res;
}
@Override
public void run(){
try{
res.methodOne(Thread.currentThread().getName(),num);
}catch(Exception e){
System.out.println(e);
}
}
}
public class LockCountPractise{
public static void main(String [] args){
SharedResource resource = new SharedResource();
MyRequestREQ[] requests = new MyRequestREQ[]{
new MyRequestREQ(resource,"JACK"),
new MyRequestREQ(resource,"JILL"),
new MyRequestREQ(resource,"JASON")
};
for(int x=0; x < requests.length;x++){
requests[x].start();
}
}
}
但是我得到的输出全部由线程“JACK”运行,该线程一直打印到计数15,然后挂断了电话。
上面的程序是否面临死锁问题?
我需要在SharedResource类的所有方法中解锁锁吗?
等待建议。
最佳答案
您没有在method3中解锁,因此当第一个线程完成后,其他线程将无法继续,因为它们无法获取锁定。
是的,因为每次您调用lock()
时:
看:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html#lock%28%29
作为建议:您可以在method1中获取锁定,然后在method3中释放它。所以会有1个锁1个解锁,您会没事的。无需3个解锁周期。
实际上,这取决于您想要的行为: