java多線程編程中,如果線程鎖使用不當,就會產生死鎖,以下是一個簡單的死鎖示例。
public class DeadRunnable implements Runnable{
Object locka=new Object();
Object lockb=new Object();
boolean flag;
public DeadRunnable(boolean flag) {
super();
this.flag = flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
//嵌套鎖,會產生死鎖問題
@Override
public void run() {
if(flag){
while(true){
synchronized(locka){
System.out.println(Thread.currentThread().getName()+"....if locka");
synchronized(lockb){
System.out.println(Thread.currentThread().getName()+"....if lockb");
}
}
}
}else{
while(true){
synchronized(lockb){
System.out.println(Thread.currentThread().getName()+"....else lockb");
synchronized(locka){
System.out.println(Thread.currentThread().getName()+"....else locka");
}
}
}
}
}
}
import org.junit.Test;
public class DeadLock {
@Test
public void testDeadLock(){
DeadRunnable d=new DeadRunnable(true);
Thread t1=new Thread(d);
Thread t2=new Thread(d);
t1.start();
//主線程睡眠10毫秒,用來設置DeadRunnable的flag值
try {
Thread.currentThread().sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
d.setFlag(false);
t2.start();
}
}
死鎖分析:線程1佔有locka,請求loackb,且在獲得lockb前不會釋放locka;線程2佔有lockb,請求locka,且在獲得locka前不會釋放lockb。這就造成互相請求對方資源的僵局,任何一個線程都無法向前推進,進而產生鎖。