线程死锁

线程死锁概念

两个线程A/B,A线程掌握着实例1的锁,要访问实例2的synchronized方法,但是实例2的锁被B所掌握着,然而B这时候又要访问实例1的synchronized方法,两个线程一直等着对方释放实例1/实例2的锁,造成程序无法进行下去,这种现象称为线程访问的死锁

代码示例

package test;

public class ThreadDeadLock {

    public static void main(String[] args) {
        Object a = new Object();
        Object b = new Object();

        MyThread1 t1 = new MyThread1(a, b);
        MyThread2 t2 = new MyThread2(a, b);

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

    }

}

class MyThread1 extends Thread {
    private Object a;
    private Object b;

    public MyThread1(Object a, Object b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public void run() {
        synchronized (a) {
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }

            synchronized (b) {

            }
        }
    }
}

class MyThread2 extends Thread {
    private Object a;
    private Object b;

    public MyThread2(Object a, Object b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public void run() {

        synchronized (b) {

            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }

            synchronized (a) {

            }
        }

    }
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mweibiao/article/details/80343521
个人分类: java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

线程死锁

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭