java 死锁产生的四个必要条件:
- 1、互斥使用,即当资源被一个线程使用(占有)时,别的线程不能使用
- 2、不可抢占,资源请求者不能强制从资源占有者手中夺取资源,资源只能由资源占有者主动释放。
- 3、请求和保持,即当资源请求者在请求其他的资源的同时保持对原有资源的占有。
- 4、循环等待,即存在一个等待队列:P1占有P2的资源,P2占有P3的资源,P3占有P1的资源。这样就形成了一个等待环路。
package com.thread;import java.util.Date;import java.util.concurrent.TimeUnit;/** * * @author zy * */public class LockTest { public static void main(String[] args) { String o1 = "o1"; String o2 = "o2"; String o3 = "o3";
new Thread(new LockA(o1, o2), "t1").start();
new Thread(new LockA(o2, o1), "t2").start(); //new Thread(new LockA(o2, o3), "t2").start(); // new Thread(new LockA(o3, o1), "t3").start();}}class LockA implements Runnable { private String o1; private String o2; public LockA(String o1, String o2) { this.o1 = o1; this.o2 = o2; } public void run() { try { String name = Thread.currentThread().getName(); System.out.println(new Date().toString() + " " + name + " " + " acquiring lock on " + o1); synchronized (o1) { System.out.println(new Date().toString() + " " + name + " " + " lock on " + o1); TimeUnit.MILLISECONDS.sleep(300); System.out.println(new Date().toString() + " " + name + " " + " acquiring lock on " + o2); synchronized (o2) { System.out.println(new Date().toString() + " " + name + " " + " lock on " + o2); TimeUnit.MILLISECONDS.sleep(300); } System.out.println(new Date().toString() + " " + name + " released lock on " + o2); } System.out.println(new Date().toString() + " " + name + " released lock on " + o1); System.out.println(new Date().toString() + " " + name + " finished execution."); } catch (Exception e) { e.printStackTrace(); } }}
运行结果为:
Fri May 05 09:53:55 CST 2017 t2 acquiring lock on o2
Fri May 05 09:53:55 CST 2017 t2 lock on o2Fri May 05 09:53:55 CST 2017 t1 acquiring lock on o1Fri May 05 09:53:55 CST 2017 t1 lock on o1Fri May 05 09:53:55 CST 2017 t1 acquiring lock on o2Fri May 05 09:53:55 CST 2017 t2 acquiring lock on o1这是两个线程死锁的时候,也可以让多个线程相互之间关联形成死锁,将注释去掉,再把第二个线程注释掉,就有三个资源相互关联的线程,运行结果:
Fri May 05 10:06:07 CST 2017 t3 acquiring lock on o3
Fri May 05 10:06:07 CST 2017 t3 lock on o3Fri May 05 10:06:07 CST 2017 t1 acquiring lock on o1Fri May 05 10:06:07 CST 2017 t1 lock on o1Fri May 05 10:06:07 CST 2017 t2 acquiring lock on o2Fri May 05 10:06:07 CST 2017 t2 lock on o2Fri May 05 10:06:07 CST 2017 t3 acquiring lock on o1Fri May 05 10:06:07 CST 2017 t2 acquiring lock on o3Fri May 05 10:06:07 CST 2017 t1 acquiring lock on o2