现在的面试挺蛋疼,为了考察大家的语言掌握水平,类似这样的题特别多,不过在某个角度来说确实能看出一个人对某个知识点的理解,就比如今天这个死锁的小例子,主要考察大家对线程死锁概念的理解程度,也考察大家对java语言的敲代码水平,下面是一个死锁的简单例子:
<span style="font-size:18px;">class Test implements Runnable { private boolean flag; //flag标签,让t1和t2线程执行不同代码 public Test(boolean flag) { this.flag=flag; } public void run() { if (flag) { synchronized(MyLock.lock1) { System.out.println("if1"); synchronized(MyLock.lock2) { System.out.println("if2"); } } } else { synchronized(MyLock.lock2) { System.out.println("else2"); synchronized(MyLock.lock1) { System.out.println("else1"); } } } } } class MyLock //两个锁,用来制造死锁 { public static Object lock1 = new Object(); public static Object lock2 = new Object(); } class DeadLock { public static void main(String[] args) { Thread t1 = new Thread(new Test(true)); //t1先用锁1再用锁2 Thread t2 = new Thread(new Test(false));//t2先用锁2再用锁1 t1.start(); t2.start(); } } </span>
原文地址:http://blog.csdn.net/seraphme1/article/details/45424299