- 死锁的简单解析是,当有两个线程A,B分别对对象a,b进行了加锁,然后再A线程中需要使用对象b方法,这时需要对对象b进行加锁,当时对象b已经被线程B加锁了,所以线程A阻塞,等待线程B释放对象b的同步锁。然后呢,线程B又需要用到对象a,对象a被线程A加锁了,所以现场B也是阻塞,等待线程A释放对象a的线程锁。这样一来,两个线程就“僵持”住了 ,这样程序既不会抛出异常,也不会继续执行----进入了死锁状态。
- 以下为代码示例,好好参悟~~
class B{ public synchronized void bar(A a){ System.out.println("当前线程名: " + Thread.currentThread().getName() + " 进入了B实例的bar方法"); try{ Thread.sleep(200); }catch (InterruptedException e){ e.printStackTrace(); } System.out.println("当前线程名: " + Thread.currentThread().getName() + " 企图调用A实例的last方法"); a.last(); } public synchronized void last(){ System.out.println("进入了B类的last方法"); } } public class A { public synchronized void foo(B b) { System.out.println("当前线程名: " + Thread.currentThread().getName() + " 进入了A示例的foo方法 "); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("当前线程名: " + Thread.currentThread().getName() +" 试图调用B示例的last方法 "); b.last(); } public synchronized void last(){ System.out.println("进入了A类的last方法"); } } class DeadLock implements Runnable{ A a = new A(); B b = new B(); public void init(){ Thread.currentThread().setName("主线程"); a.foo(b); System.out.println("进入了主线程之后"); } 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(); } }
java多线程(9)死锁
最新推荐文章于 2022-07-12 14:03:20 发布