java 线程死锁

java线程死锁

java线程死锁代码示例:

通过lock实现死锁

public class DeadLockTest {
    Lock lock1 = new ReentrantLock(true);
    Lock lock2 = new ReentrantLock(true);

    public void test1() throws InterruptedException {
        lock1.lock();
        Thread.sleep(3000);
        System.out.println("lock1");
        test2();
        lock1.unlock();
    }
    public void test2() throws InterruptedException {
        lock2.lock();
        Thread.sleep(3000);
        System.out.println("lock2");
        test1();
        lock2.unlock();
    }
    public static void main(String[] args) {
        final DeadLockTest deadLockTest = new DeadLockTest();

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                try {
                    deadLockTest.test1();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                try {
                    deadLockTest.test2();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}

先创建两个线程锁lock1、lock2,test1()方法中请求lock1锁,锁住test1,然后
让线程1sleep(让另一线程能够有足够时间请求对test2()的lock锁),在test2()方法中请求lock2锁,同样让线程2sleep,这样两个线程都有足够时间获取锁。这样就形成了两个线程互相等待对方释放锁,不然程序就无法继续运行下去,形成了死锁的局面。

运行结果:

程序在这个情况下一直处于死锁状态,程序的状态仍然处于运行状态,只要两个线程都不释放手中的锁,那么程序就会一直僵持在这种状态持续下去。

通过synchronized实现死锁

public class DeadLockTest2{

    Object oa = new Object();
    Object ob = new Object();

    public void m1(){
        //锁住oa对象
        synchronized (oa){
            System.out.println("m1 start ...");

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //尝试获取ob的锁
            synchronized (ob){
                System.out.println("got ob lock ...");
            }
            System.out.println("m1 end ...");
        }
    }

    public void m2(){
        //锁住ob对象
        synchronized (ob){
            System.out.println("m2 start ...");
            //尝试获取oa对象的锁
            synchronized (oa){
                System.out.println("got oa lock ...");
            }
            System.out.println("m2 end ...");
        }
    }

    public static void main(String[] args) {
        final DeadLockTest2 deadLock = new DeadLockTest2();
        new Thread(new Runnable() {
            @Override
            public void run() {
                deadLock.m1();
            }
        },"thread 1").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                deadLock.m2();
            }
        },"thread 2").start();
    }
}

运行结果
image

posted @ 2020-09-06 19:39  TidalCoast  阅读(136)  评论(0编辑  收藏  举报