关于“死锁”,《JAVA开发实战经典》一书上有个例子,我小改了一下,感觉这样容易理解些,这样的思路是否正确?运行结果是一样的。
class ZhangSan
{
public void say(){
System.out.println("张三对李四说:“你给我画,我就把书给你。”");
}
public void get(){
System.out.println("张三得到画了。");
}
public void give(){
System.out.println("张三把书给李四了。");
}
};
class LiSi
{
public void say(){
System.out.println("李四对张三说:“你给我书,我就把画给你。”");
}
public void get(){
System.out.println("李四得到书了。");
}
public void give(){
System.out.println("李四把画给张三了。");
}
};
class Exchange implements Runnable
{
private ZhangSan zs;
private LiSi ls;
private boolean flag;
public Exchange(ZhangSan zs,LiSi ls,boolean flag){
this.zs = zs;
this.ls = ls;
this.flag = flag;
}
public void run(){
if (this.flag)
{
synchronized(zs){
zs.say();
synchronized(ls){
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
ls.give();
}
zs.get();
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
zs.give();
}
}else{
synchronized(ls){
ls.say();
synchronized(zs){
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
zs.give();
}
ls.get();
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
ls.give();
}
}
}
};
public class ThreadDeadLock
{
public static void main(String args[]){
ZhangSan zs = new ZhangSan();
LiSi ls = new LiSi();
Exchange e1 = new Exchange(zs,ls,true);
Exchange e2 = new Exchange(zs,ls,false);
new Thread(e1).start();
new Thread(e2).start();
}
};