public class Deadlock{
public static void main(String[] args){
Object O1 = new Object();
Object O2 = new Object();
Thread1 S1 = new Thread1(O1,O2);
Thread2 S2 = new Thread2(O1,O2);
S1.start();
S2.start();
}
}
class Thread1 extends Thread{
Object O1;
Object O2;
Thread1(Object o1,Object o2){
O1 = o1;
O2 = o2;
}
public void run(){
System.out.println("i am thread 1----");
synchronized (O2){
System.out.println("i get synchronized O2,need synchronized O1----");
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
synchronized (O1){
System.out.println("i need synchronized O1----");
}
}
}
}
class Thread2 extends Thread{
Object O1;
Object O2;
Thread2(Object o1,Object o2){
O1 = o1;
O2 = o2;
}
public void run(){
System.out.println("i am thread 2----");
synchronized (O1){
System.out.println("i get synchronized O1,need synchronized O2----");
try{
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
synchronized (O2){
System.out.println("i need synchronized O2----");
}
}
}
}
产生死锁的四个必要条件:(1) 互斥条件:一个资源每次只能被一个线程使用。
(2) 请求与保持条件:一个线程因请求资源而阻塞时,对已获得的资源保持不放。
(3) 不剥夺条件:线程已获得的资源,在末使用完之前,不能强行剥夺。
(4) 循环等待条件:若干线程之间形成一种头尾相接的循环等待资源关系。