死锁,就是一堆线程或进程,各自都想运行,但都缺资源运行不了,而这些资源若在不破除死锁四个必要条件(互斥、请求与保持、不可剥夺、循环等待)的情况下,谁也拿不到资源去运行。例子,假如俩人要抽烟,抽烟要打火机和香烟,A持有了打火机,B持有了香烟,谁也不肯在完成抽烟之前释放手中的打火机或香烟,于是俩人就都抽不到烟,形成僵持局面,这种僵持局面就是死锁。以下用Java代码模拟。
//main中加入
//Smoke m1 = new Smoke(0, "A");//选择0先拿打火机
//Smoke m2 = new Smoke(1, "B");//选择1先拿香烟
//m1.start();
//m2.start();
//main中加入
class Cigar{
}
class Lighter{
}
class Smoke extends Thread{
static Cigar cigar = new Cigar();
static Lighter lighter = new Lighter();
int choice;
String man;
public Smoke(int choice, String man) {
super();
this.choice = choice;
this.man = man;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
inhale();
}
private void inhale() {
if(choice == 0) {
synchronized(lighter){
System.out.println(this.man + " get lighter");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (cigar) {
System.out.println(this.man + " get cigar");
}
}
}
else{
synchronized(cigar){
System.out.println(this.man + " get cigar");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (lighter) {
System.out.println(this.man + " get lighter");
}
}
}
}
}