日期:2014-05-20  浏览次数:20694 次

谁能写一个简单的线程死锁出来
小弟写出来的死锁在Eclipse里不生效,程序还是退出了,不知道啥原因
Java code

if(flag==0){
                synchronized(o1){
                    System.out.println("0--开始锁住o1");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {}
                synchronized(o2){
                    System.out.println("0--开始锁住o2");
                    LockTest.m("0"+Thread.currentThread().getName());
                }
                }
            }
            
            if(flag==1){
                synchronized(o2){
                    System.out.println("1--开始锁住o2");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {}
                }
                synchronized(o1){
                    System.out.println("1--开始锁住o1");
                    LockTest.m("1"+Thread.currentThread().getName());
                }
            }



------解决方案--------------------
public class Deadlock {

public static void main(String args[]) {
final Object resource1 = "resource1";
final Object resource2 = "resource2";
Thread t1 = new Thread() {

@Override
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked resource 1");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
synchronized (resource2) {
System.out.println("Thread1: locked resource 2");
}
}
}
};

Thread t2 = new Thread() {

@Override
public void run() {
synchronized (resource2) {
System.out.println("Thread2: locked resource 2");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
synchronized (resource1) {
System.out.println("Thread2: lock resource 1");
}
}
}
};

t1.start();
t2.start();
}
}