手写一个死锁、死锁满足的条件
1、至少有两个线程互相争夺共享资源
2、至少有两把锁两个线程分别持有锁
两个线程各自持有一把锁并且企图获取到对方的正在持有的锁
package demos; import java.util.concurrent.TimeUnit; /** * 写一个死锁第一种写法 */ public class DeadLock { public static void main(String[] args) { String a = "a"; String b = "b"; new Thread(new Resource(a,b),"ThreadA").start(); new Thread(new Resource(b,a),"ThreadB").start(); } } class Resource implements Runnable{ String a; String b; public Resource(String a,String b){ this.a = a; this.b = b; } @Override public void run() { synchronized (a){ System.out.println(Thread.currentThread().getName()); try { TimeUnit.SECONDS.sleep(2L); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (b){ System.out.println(Thread.currentThread().getName()); } } } }
package demos; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 写一个死锁第二种写法用lock */ public class DeadLock1 { public static void main(String[] args) { Lock lock1 = new ReentrantLock(); Lock lock2 = new ReentrantLock(); new Thread(new Resource1(lock1,lock2),"A").start(); new Thread(new Resource1(lock2,lock1),"B").start(); } } class Resource1 implements Runnable{ Lock lock1; Lock lock2; public Resource1(Lock lock1,Lock lock2){ this.lock1 = lock1; this.lock2 = lock2; } @Override public void run() { lock1.lock(); try{ System.out.println(Thread.currentThread().getName()); Thread.sleep(2); lock2.lock(); try{ System.out.println(Thread.currentThread().getName()); }finally { lock2.unlock(); } } catch (InterruptedException e) { e.printStackTrace(); } finally { lock1.unlock(); } } }