java死锁
一. 什么是死锁
在多线程程序中,使用了多把锁,造成线程之间相互等待,程序不往下走了。
二. 产生死锁的条件
- 有多把锁
- 有多个线程
- 有(sychronized)同步代码块嵌套:自己才能指定锁对象
//死锁演示代码,不增加Thread.sleep(1000);语句的话,有可能不会产生死锁现象。
public class test {
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
synchronized ("锁A"){
System.out.println("thread1:take lock a,to take lock b...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized ("锁B"){
System.out.println("thread1:take lock a and b,to start");
}
}
}
},"thread1").start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized ("锁B"){
System.out.println("thread2:take lock b,to take lock a...");
synchronized ("锁A"){
System.out.println("thread2:take lock b and a,to start");
}
}
}
},"thread2").start();
}
}
浙公网安备 33010602011771号