Java + 线程系列之死锁(六)

** //sleep与wait的区别
// sleep对象不会释放锁对象
// wait会释放锁对象
**“`
//创建一个类
public class PrinterDeadLock {
private String s1 = “我是s1”;
private String s2 = “我是s2”;

public void p1() {
    synchronized (s1) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            //s1是锁对象,调用了s1锁对象的wait方法
            //wait方法,会释放锁对象
            //并且,使得线程进入阻塞状态
           s1.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("s1锁住了p1");

        synchronized (s2) {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("s2锁住了p1");
            }
        }
    }
}

public void p2() {
    synchronized (s2) {
        System.out.println("s2锁住了p2");

        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (s1) {

                System.out.println("s1锁住了p2");

                //调用s1锁对象的
                //notifyAll方法
                //会唤醒被s1调用wait方法
                // 进入阻塞状态的线程
                s1.notifyAll();
            }
        }
    }

}

}

//Main函数中调用
private static void showDeadLock() {
PrinterDeadLock pdl = new PrinterDeadLock();
new Thread(new Runnable() {
@Override
public void run() {
pdl.p1();
}
}).start();

    //JNI  --java native interface
    new Thread(new Runnable() {
        @Override
        public void run() {
            pdl.p2();
        }
    }).start();
}

“`
运行结果:Java + 线程系列之死锁(六)_第1张图片

你可能感兴趣的:(java,线程锁)