zranye 发表于 2013-2-3 10:32:16

关于java的死锁DeadLock

    看scjp考题的时候,关于一道多线程题目,总是不能把它推成死锁,郁闷之下,一看答案,原来真的不是死锁,可是为什么我老是想要把它推成死锁呢?很明显,是没有学到家。所以,翻箱倒柜查完资料之后,写出一个死锁Demo,来确定自己确实知道了什么是死锁。
 
 
public class DeadLockDemo {public static void main(String[] args) {final String lock1 = "LOCK1";final String lock2 = "LOCK2";Thread t1 = new Thread(){public void run() {synchronized (lock1) {System.out.println("t1:Locking Source1");try {sleep(1500);} catch (InterruptedException e) {e.printStackTrace();}synchronized (lock2) {System.out.println("t1:Locking Source2");}}}};Thread t2 = new Thread(){public void run(){synchronized (lock2) {System.out.println("t1:Locking Source1");try {sleep(1500);} catch (InterruptedException e) {e.printStackTrace();}synchronized (lock1) {System.out.println("t2:Locking Source1");}}}};                t1.start();t2.start();}} 
    /*Output:
 
t1:Locking Source1t2:Locking Source2    *///:~
    一个简单死锁的小小实例。


    关于“锁”还有点懵懂,希望以后能慢慢领悟。
页: [1]
查看完整版本: 关于java的死锁DeadLock