我写了个死锁的小程序,但是执行出来却不是死锁,而且我执行的其它多线程程序也有问题,我想问下各位是我的程序有问题还是其它原因啊?程序如下:package test.thread;public class DeadClock implements Runnable{

int flag=0;
static Object o1=new Object();
static Object o2=new Object();
/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
DeadClock d=new DeadClock();
DeadClock d1=new DeadClock();
d.flag=0;
d1.flag=1;
Thread t1=new Thread(d);
Thread t2=new Thread(d1);
t1.start();
t2.start(); }
public void run(){
if(flag==1){
synchronized(o1){
try{
Thread.sleep(1000);
}catch(InterruptedException e){

}
System.out.println(flag);
}
synchronized(o2){
System.out.println("end");
}
}
if(flag==0){
synchronized(o2){
try{
Thread.sleep(1000);
}catch(InterruptedException e){

}
System.out.println(flag);
}
synchronized(o1){
System.out.println("end");
}
}
}}

解决方案 »

  1.   

    代码应该市这样,就会死锁了
    public class DeadClock implements Runnable { int flag = 0;
    static Object o1 = new Object();
    static Object o2 = new Object(); /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    DeadClock d = new DeadClock();
    DeadClock d1 = new DeadClock();
    d.flag = 0;
    d1.flag = 1;
    Thread t1 = new Thread(d);
    Thread t2 = new Thread(d1);
    t1.start();
    t2.start(); } public void run() {
    if (flag == 1) {
    synchronized (o1) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) { }
    System.out.println(flag);
    synchronized (o2) {
    System.out.println("end");
    }
    } }
    if (flag == 0) {
    synchronized (o2) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) { }
    System.out.println(flag);
    synchronized (o1) {
    System.out.println("end");
    }
    } }
    }}
      

  2.   

    LZ的代码:
    public void run() {
    if (flag == 1) {
    synchronized (o1) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) { }
    System.out.println(flag);
    //我的synchronized (o2)在这里
    }
    synchronized (o2) {
    System.out.println("end");
    }
    }
    if (flag == 0) {
    synchronized (o2) {
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) { }
    System.out.println(flag);
    //我的synchronized (o1)在这里
    }
    synchronized (o1) {
    System.out.println("end");
    }
    }
    }
    找个IDE来写代码吧