java线程死锁问题

public class TestDeadLock implements Runnable {
    public static int flag =1;
    public static Object o1;
    public static Object o2;

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("flag = "+flag);
        if(flag == 1){
            synchronized(o1){
                try {
                    Thread.sleep(5000);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            synchronized (o2) {
                System.out.println("1");
            }
        }
        if(flag == 0){
            synchronized (o2) {
                try {
                    Thread.sleep(5000);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("0");
                }
            }
        }
    }
    public static void main(String[] args) {
        TestDeadLock td1 = new TestDeadLock();
        TestDeadLock td2 = new TestDeadLock();
        td1.flag = 1;
        td2.flag = 0;
        Thread t1 = new Thread(td1);
        Thread t2 = new Thread(td2);
        t1.start();
        t2.start();
    }
}

flag = 0Exception in thread "Thread-0" Exception in thread "Thread-1"
flag = 0
java.lang.NullPointerException
    at Thread.TestDeadLock.run(TestDeadLock.java:26)
    at java.lang.Thread.run(Unknown Source)
java.lang.NullPointerException
    at Thread.TestDeadLock.run(TestDeadLock.java:26)
    at java.lang.Thread.run(Unknown Source)
上面是运行结果,编译没有问题,求解释。

superkrissV
浏览 1972回答 1
1回答

蓝胖子Torres

空指针了,要把o1和o2先实例化,才能给它加锁
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java