java死锁情况问题
public class DeadLock { public static void main(String[] args) { ResouceLocktask resouceLocktask = new ResouceLocktask(); new Thread(resouceLocktask, "线程A").start(); new Thread(resouceLocktask, "线程B").start(); } } class ResouceLocktask implements Runnable{ private Object o1 = new Object(); private Object o2 = new Object(); private boolean flag = true; @Override public void run() { if(flag){ flag = false; synchronized (o1) { System.out.println(Thread.currentThread().getName()+"锁住资源o1,等到o2"); try { //这里的目的是 Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (o2) { System.out.println(Thread.currentThread().getName()+"得到资源o2"); } } }else{ flag = true; synchronized (o2) { System.out.println(Thread.currentThread().getName()+"锁住资源o2,等到o1"); try { //这里的目的是防止一下获取到两个锁 Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (o1) { System.out.println(Thread.currentThread().getName()+"得到资源o1"); } } } } }
为什么这段代码能产生死锁啊,它两个线程用的应该不是同一把锁,因为我在网上看到写死锁的情况,都会在private static Object这么写,如果不这么写,就不会产生死锁。但是这个例子会产生死锁,是为什么啊,真心求教!!!!!!
#Java##笔试题目#