线程死锁

所谓的线程死锁,是指在多线程运行的过程中,线程1拥有锁a,而需要锁b来继续执行,
 
而此时,线程2拥有锁b而需要锁a来继续执行,那么此时会形成死锁,两个线程会同时等待。
在编程的过程中应尽量的避免线程死锁。
关于线程锁可以查看:线程锁详解
有时在面试中会要求写出一个死锁的程序演示,如下:
 1 //写一个死锁程序
 2 public class DeadLock {
 3      //主程序执行
 4      public static void main(String[] args) {
 5           Thread thread1 = new Thread(new MyThread(true));
 6           Thread thread2 = new Thread(new MyThread(true));
 7           thread1.start();
 8           thread1.start();
 9           thread2.start();
10      }
11 }
12 class MyThread implements Runnable{
13      private boolean flag;
14      //标记,用来分割线程执行部分
15      public MyThread(boolean flag) {
16           this.flag = flag;
17      }
18      @Override
19      public void run() {
20           if (flag) {
21                //线程1拥有锁1而需要锁2
22               synchronized(MyLock.object1) {
23                    System.out.println("锁1");
24                    synchronized(MyLock.object2) {
25                         System.out.println("锁2");
26                    }
27               }
28           }else {
29                //线程2拥有锁2而需要锁1
30               synchronized(MyLock.object2) {
31                    System.out.println("锁2");
32                    synchronized(MyLock.object1) {
33                         System.out.println("锁1");
34                    }
35               }
36           }
37 
38      }
39 }
40 class MyLock{
41      //创建两个显式的锁
42      static Object object1 = new Object();
43      static Object object2 = new Object();
44 }
原文地址:https://www.cnblogs.com/anzhi/p/7465153.html