死锁:线程A持有一个对象a1的互斥锁,又试图获取另外一个对象b1的互斥锁,而线程B正好持有对象a1的互斥锁,并且试图获取对象b1的互斥锁,2个线程相互等待对方的资源而又互相不作出让步。
<span style="font-size:14px;">package com.test;
/**
* 死锁测试
* @author mooner
*
*/
public class DeadThreadLock {
public static void main(String[] args) {
String s1 = "a";
String s2 = "b";
ThreadLock t1 = new ThreadLock(s1,s2); //持有"a"的互斥锁,尝试获取"b"的互斥锁
t1.start();
ThreadLock t2 = new ThreadLock(s2,s1); //持有"b"的互斥锁,尝试获取"a"的互斥锁
t2.start();
}
}
/**
* 死锁多线程
* @author mooner
*
*/
class ThreadLock extends Thread{
private String s1;
private String s2;
public ThreadLock(){
}
public ThreadLock(String s1,String s2){
this.s1 = s1;
this.s2 = s2;
}
public void run(){
synchronized(s1){ //获取s1对象的互斥锁
System.out.println(Thread.currentThread().getName() +"持有对象 "+s1+" 的锁");
try {
Thread.sleep(4000); //睡眠4s钟,好在获取s2对象的互斥锁前,另外一个线程开始运行
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +"尝试获取 "+s2+" 的锁");
synchronized(s2){ //获取s2对象的互斥锁子
}
}
}
}</span>