Java多线程中,如何分析并解决一个典型的死锁案例?
- 内容介绍
- 文章标签
- 相关推荐
本文共计221个文字,预计阅读时间需要1分钟。
在多线程环境中,线程6和线程7试图访问对方持有的资源,导致死锁。以下是简化后的代码内容:
javapackage cn.mym.thread;
public class TestExclusionThread { static Object obj1=new Object(); static Object obj2=new Object();
public static void main(String[] args) { Thread t1=new Thread(() -> { synchronized (obj1) { System.out.println(Thread6: 占用 obj1); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj2) { System.out.println(Thread6: 占用 obj2); } } });
Thread t2=new Thread(() -> { synchronized (obj2) { System.out.println(Thread7: 占用 obj2); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj1) { System.out.println(Thread7: 占用 obj1); } } });
t1.start(); t2.start(); }}
thread6占用thread7需要的资源,thread7占用thread6需要的资源,最终导致死锁package cn.mym.thread; public class TestExclusionThread { static Object obj1 = new Object(); static Object obj2 = new Object(); public static void main(String[] args) { Thread6 t1 = new Thread6(); Thread7 t2 = new Thread7(); t1.start(); t2.start(); //System.out.println("ashfkdhsf"); } static class Thread6 extends Thread{ @Override public void run() { synchronized(obj1){ System.out.println("obj1锁住了"); synchronized(obj2){ //锁住obj2 } } } } static class Thread7 extends Thread{ @Override public void run() { synchronized(obj2){ System.out.println("obj2锁住了"); synchronized(obj1){ //锁住obj1 } } } } }
本文共计221个文字,预计阅读时间需要1分钟。
在多线程环境中,线程6和线程7试图访问对方持有的资源,导致死锁。以下是简化后的代码内容:
javapackage cn.mym.thread;
public class TestExclusionThread { static Object obj1=new Object(); static Object obj2=new Object();
public static void main(String[] args) { Thread t1=new Thread(() -> { synchronized (obj1) { System.out.println(Thread6: 占用 obj1); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj2) { System.out.println(Thread6: 占用 obj2); } } });
Thread t2=new Thread(() -> { synchronized (obj2) { System.out.println(Thread7: 占用 obj2); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj1) { System.out.println(Thread7: 占用 obj1); } } });
t1.start(); t2.start(); }}
thread6占用thread7需要的资源,thread7占用thread6需要的资源,最终导致死锁package cn.mym.thread; public class TestExclusionThread { static Object obj1 = new Object(); static Object obj2 = new Object(); public static void main(String[] args) { Thread6 t1 = new Thread6(); Thread7 t2 = new Thread7(); t1.start(); t2.start(); //System.out.println("ashfkdhsf"); } static class Thread6 extends Thread{ @Override public void run() { synchronized(obj1){ System.out.println("obj1锁住了"); synchronized(obj2){ //锁住obj2 } } } } static class Thread7 extends Thread{ @Override public void run() { synchronized(obj2){ System.out.println("obj2锁住了"); synchronized(obj1){ //锁住obj1 } } } } }

