java死锁

一. 什么是死锁

  在多线程程序中,使用了多把锁,造成线程之间相互等待,程序不往下走了。

 

二. 产生死锁的条件

  1. 有多把锁
  2. 有多个线程
  3. (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();
}
}
posted @ 2022-02-22 22:13  -YBP杨社长  阅读(43)  评论(0)    收藏  举报