1.概念

两个或多个进程在执行的过程中,因为竞争资源而造成互相等待的现象

 

2.Demo

看下面的例子,对概念有个更加清晰的认识。

 1 public class DeadLockDemo {
 2 
 3     public static void main(String[] args) {
 4         
 5         Object a = new Object();
 6         Object b = new Object();
 7         
 8         new Thread(new Runnable() {
 9             
10             @Override
11             public void run() {
12                 synchronized (a) {
13                     try {
14                         System.out.println("Thread 1 started");
15                         System.out.println("Got the lock of Object a");
16                         Thread.sleep(1000);
17                     } catch (InterruptedException e) {
18                         e.printStackTrace();
19                     }
20                     System.out.println("Try to get the lock of Object b");
21                     synchronized (b) {
22                     }
23                 }
24             }
25         }).start();
26         
27         new Thread(new Runnable() {
28             
29             @Override
30             public void run() {
31                 synchronized (b) {
32                     try {
33                         System.out.println("Thread 2 started");
34                         System.out.println("Got the lock of Object b");
35                         Thread.sleep(1000);
36                     } catch (InterruptedException e) {
37                         e.printStackTrace();
38                     }
39                     System.out.println("Try to get the lock of Object a");
40                     synchronized (a) {
41                     }
42                 }
43             }
44         }).start();
45     }
46 }
View Code

相关文章:

  • 2021-10-23
  • 2021-05-21
  • 2021-04-06
  • 2021-12-10
  • 2021-08-19
猜你喜欢
  • 2021-06-10
  • 2021-09-25
  • 2021-10-19
  • 2021-12-10
  • 2021-12-24
相关资源
相似解决方案