class DeadLock extends Thread{
//新建两个对象锁
static String str1 = new String();
static String str2 = new String();
public void run() {
//创建同步代码块
synchronized(str1){
//打印线程刚获取对象锁的状态信息
System.out.println(Thread.currentThread().getName()+"已经占有了str1");
try {
//让线程t1睡眠5秒,使得线程t2有足够的时间占有str1
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"试图占有str2");
System.out.println(Thread.currentThread().getName()+"等待中...");
//该线程第二次访问同步代码块,并释放两个对象锁
synchronized(str2){
System.out.println(Thread.currentThread().getName()+"已经占有str1和str2");
}
}
}
}
//新建一个子类继承DeadLock,代码内容与上面基本相同
class DeadLock2 extends DeadLock{
public void run(){
synchronized(str2){
System.out.println(Thread.currentThread().getName()+"已经占有str2");
try{
Thread.sleep(3000);
}catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"试图占有str1");
System.out.println(Thread.currentThread().getName()+"等待中...");
synchronized(str1){
System.out.println(Thread.currentThread().getName()+"已经占有了str2和str1");
}
}
}
}
/*
* 当两个线程t1和t2试图同时占有str1和str2的时候,程序会停止造成死锁
*/
public class Thread_Deadlock {
public static void main(String[] args){
DeadLock d1 = new DeadLock();
//命名线程为t1
d1.setName("t1");
d1.start();
DeadLock2 d2 = new DeadLock2();
//命名线程t2
d2.setName("t2");
d2.start();
}
}
运行的结果为:
t2已经占有str2
t1已经占有了str1
t2试图占有str1
t2等待中...
t1试图占有str2
t1等待中...