# Java高级之线程死锁 **Repository Path**: fpfgitmy_admin/java-high-thread-deadlock ## Basic Information - **Project Name**: Java高级之线程死锁 - **Description**: 线程死锁 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2021-04-28 - **Last Updated**: 2021-04-28 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### 线程的死锁问题 #### 死锁 + 不同的线程分别占用对象需要的同步资源不放弃,都在等待对方放弃自己需要的同步资源,就形成了线程的死锁。 + 出现死锁后,不会出现异常,不会出现提示,只是所有的线程都处于阻塞状态,无法继续。 #### 解决方法 + 专门的算法、原则 + 精良减少同步资源的定义 + 精良避免嵌套同步 #### 简单的线程死锁 ###### 线程死锁-1 ``` package com.felixfei.study.threads; /** * @describle 线程的死锁问题 */ public class ThreadSynTest { public static void main(String[] args) { StringBuffer s1 = new StringBuffer(); StringBuffer s2 = new StringBuffer(); new Thread() { @Override public void run() { synchronized (s1) { s1.append("a"); s2.append("1"); // 使用sleep增加死锁概率(死锁原因:当第一个线程使用s1同步监视器,并且占用了资源s1和s2的时候,第二个线程也有可能执行,当第二个线程执行的时候到下一步的时候需要名为s1同步监视器,第一个线程执行到第二步的时候需要名为s2的同步监视器,却发现对象都在分别使用s1和s2同步监视器,都在等待对象放开,所以造成死锁) try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (s2) { s1.append("b"); s2.append("2"); System.out.println(s1); System.out.println(s2); } } } }.start(); new Thread(new Runnable() { @Override public void run() { synchronized (s2) { s1.append("c"); s2.append("3"); // 使用sleep增加死锁概率 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (s1) { s1.append("d"); s2.append("4"); System.out.println(s1); System.out.println(s2); } } } }).start(); } } ``` ##### 线程死锁-2 ``` package com.felixfei.study.threads; /** * @describle 线程死锁问题 */ public class DeadLock implements Runnable { A a = new A(); B b = new B(); public void init() { Thread.currentThread().setName("主线程"); a.foo(b); System.out.println("进入主线程后"); } @Override public void run() { Thread.currentThread().setName("副线程"); b.bar(a); System.out.println("进入副线程后"); } public static void main(String[] args) { DeadLock deadLock = new DeadLock(); // 副线程 new Thread(deadLock).start(); // 主线程 deadLock.init(); } } class A { public synchronized void foo(B b) { // 同步监视器a System.out.println("当前线程名:" + Thread.currentThread().getName() + "进入了A实例的foo方法"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("当前线程名:" + Thread.currentThread().getName() + "企图调用B实例的last方法"); b.last(); } public synchronized void last() { // 同步监视器a System.out.println("进入了A类的last方法内部"); } } class B { public synchronized void bar(A a) { // 同步监视器a System.out.println("当前线程名:" + Thread.currentThread().getName() + "进入了B实例的bar方法"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("当前线程名:" + Thread.currentThread().getName() + "企图调用B实例的last方法"); a.last(); } public synchronized void last() { // 同步监视器b System.out.println("进入了B类的last方法内部"); } } ```