线程死锁
多线程并发时,除了容易出现线程安全和数据不同问题外,还容易出现另一种情况:多个线程都在等待被对方占有的资源释放,此时程序会陷入一个僵局,这种状态就称之为死锁
public class DeadLock implements Runnable{
private int id;
//声明两个静态的引用类型对象
private static Object obj1 = new Object();
private static Object obj2 = new Object();
public DeadLock(int id) {
super();
this.id = id;
}
@Override
public void run() {
if(id == 1){
synchronized (obj1) {
try {
System.out.println("线程"+id+"已锁定obj1,等待锁定obj2");
Thread.sleep(1000);
synchronized (obj2) {
System.out.println("线程"+id+"执行结束");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}else{
synchronized (obj2) {
try {
System.out.println("线程"+id+"已锁定obj2,等待锁obj1");
Thread.sleep(1000);
synchronized (obj1) {
System.out.println("线程"+id+"执行结束");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
DeadLock d1 = new DeadLock(1);
DeadLock d2 = new DeadLock(2);
new Thread(d1).start();
new Thread(d2).start();
}
}