使用多线程方法生成一个死锁程序

来源:互联网 发布:php自动跳转url 编辑:程序博客网 时间:2024/05/16 04:51

/**
 * 要求:生成一个死锁程序
 *
 */
public class DieThreadDemo {


public static void main(String[] args) {
//创建这两个线程
Example example=new Example();
DieThread1 thread1=new DieThread1(example);
thread1.start();
DieThread2 thread2=new DieThread2(example);
thread2.start();

}


}
class DieThread1 extends Thread{
private Example example=null;

public DieThread1(Example example) {
super();
this.example = example;
}


@Override
public void run() {
example.method1();
}

}
class DieThread2 extends Thread{
private Example example=null;

public DieThread2(Example example) {
super();
this.example = example;
}

@Override
public void run() {
example.method2();
}

}
//应该尽量避免同步块中嵌套同步块
class Example{
private Object obj1=new Object();
private Object obj2=new Object();
public void method1() {
synchronized (obj1) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj2) {
System.out.println("methord1");
}
}
}
public void method2() {
synchronized (obj2) {
//想先获取object2
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj1) {
//再获取object1
System.out.println("methord2");
}
}
}
}
0 0