【Java并发编程学习】6、死锁

/**
 * 可重入内置锁
 *     每个Java对象都可以用做一个实现同步的锁,这些锁被称为内置锁或监视锁。线程在进入同步代码块之前会自动获取锁,并且在退出同步代码块时
 * 会自动释放锁。获取内置锁的唯一途径是进入由这个锁保护的同步代码块或方法。
 * “重入”意味着获取锁的操作的粒度是“线程”,而不适合调用。
 * 同一个线程在调用本类中其它synchronized方法/块或父类中的synchronized方法/块时,都不会阻碍该线程地执行,因为互斥锁时可重入的。
 */
public class Deadlock extends Object {
    private String objID;

    public Deadlock(String id) {
        objID = id;
    }

    public synchronized void checkOther(Deadlock other) {
        print("entering checkOther()");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {

        }
        print("in checkOther() - about to" + "invoke 'other.action()'");
        other.action();
        print("leaving checkOther()");
    }

    public synchronized void action() {
        print("entering action()");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {

        }
        print("leaving action()");
    }

    public void print(String msg) {
        threadPrint("objID=" + objID + "-" + msg);
    }

    public static void threadPrint(String msg) {
        String threadName = Thread.currentThread().getName();
        System.out.println("[Deadlock] threadName= " + threadName + "#" + msg);
    }

    public static void main(String[] args) {
        final Deadlock obj1 = new Deadlock("obj1");
        final Deadlock obj2 = new Deadlock("obj2");

        Runnable runA = new Runnable() {
            @Override
            public void run() {
                obj1.checkOther(obj2);
            }
        };
        Thread threadA = new Thread(runA, "threadA");
        threadA.start();

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Runnable runB = new Runnable() {
            @Override
            public void run() {
                obj2.checkOther(obj1);
            }
        };
        Thread threadB = new Thread(runB, "threadB");
        threadB.start();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        threadPrint("about to interrupt() threadA");
        threadA.interrupt();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadPrint("about to interrupt() threadB");
        threadB.interrupt();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        threadPrint("did that break the deadlock?");
    }
}

猜你喜欢

转载自my.oschina.net/u/3545495/blog/1818237
今日推荐