死锁
- 线程死锁原理图:
- 锁对象 LockA
package com.yonyou.sci.gateway.exec.sisuo; public class LockA { // 构造方法私有化,控制这个锁对象不能使用 new 来创建 private LockA(){}; static final LockA locka = new LockA(); }
- 锁对象 LockB
package com.yonyou.sci.gateway.exec.sisuo; public class LockB { // 构造方法私有化,控制这个锁对象不能使用 new 来创建 private LockB(){}; static final LockB lockb = new LockB(); }
- Runnable接口实现死锁代码
package com.yonyou.sci.gateway.exec.sisuo; /** * 实现死锁代码 * 运行 if 里面的 LockA.locka是,这时候执行 else 的 LockB.lockb 方法,就会出现死锁的情况 */ public class LockRunnable implements Runnable { int i = 0; @Override public void run () { while (true) { if( i%2 == 0){ synchronized (LockA.locka){ System.out.println("if...locka"); synchronized (LockB.lockb) { System.out.println("if...lockb"); } } } else { synchronized (LockB.lockb){ System.out.println("else...lockb"); synchronized (LockA.locka){ System.out.println("else...locka"); } } } i++; } } }
- 运行死锁代码
package com.yonyou.sci.gateway.exec.sisuo; public class LockMain { public static void main (String[] args) { LockRunnable lr = new LockRunnable(); Thread t1 = new Thread(lr); Thread t2 = new Thread(lr); t1.start();t2.start(); } }