java 死锁简单分析
1. 看一段代码关于死锁的
public class DeadLockDemo2 { public static void main(String[] args) throws InterruptedException { // 这里是创建了三个对象资源,这些资源被传入到了三个线程中,开启线程之后就会调用这三个资源的相关方法 Object obj1 = new Object(); Object obj2 = new Object(); Object obj3 = new Object(); // 这里 Thread t1 = new Thread(new SyncThread(obj1, obj2), "t1"); Thread t2 = new Thread(new SyncThread(obj2, obj1), "t2"); t1.start(); Thread.sleep(500); t2.start(); } } // 定义一个线程对象 class SyncThread implements Runnable { private Object obj1; private Object obj2; public SyncThread(Object o1, Object o2) { this.obj1 = o1; this.obj2 = o2; } @Override public void run() { String name = Thread.currentThread().getName(); System.out.println(name + " acquiring lock on " + obj1); // 两个锁对象,这了有一个线程进入之后就持有了obj1,那么另一个线程因为obj1被持有了,那么就 // 不会持有obj1,而会进入到obj2,那么线程1因为此时持有了obj1,而obj2却被另一个线程持有,那么 // 现在的线程1就没办法获取到obj2,就会一直处于等待状态,而线程2也是处于等待 synchronized (obj1) { System.out.println(name + " acquired lock on " + obj1); work(1); System.out.println(name + " acquiring lock on " + obj2); // 这里obj2被互斥 synchronized (obj2) { System.out.println(name + " acquired lock on " + obj2); work(2); } System.out.println(name + " released lock on " + obj2); } System.out.println(name + " released lock on " + obj1); System.out.println(name + " finished execution."); } private void work(int i) { try { String name = Thread.currentThread().getName(); if (i == 1) { System.out.println(name + " working sleep " + i + " # " + this.obj1); } else { System.out.println(name + " working sleep " + i + " # " + this.obj2); } Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }
通过两次的互斥,并且对不同对象进行互斥,然后两个线程持有这两个对象进行操作,就死锁了