和我一起迎接明天的太阳吧

klaus08

焦虑源于行动的匮乏

synchronized实现的死锁

创建出两个子进程,一个拥有资源A准备获取资源B,另一个拥有资源B准备获取资源A,然后构成死锁。

package com.klaus.thread;

import java.util.concurrent.locks.ReentrantLock;

public class MyDeadLock {

    public static void main(String[] args) throws InterruptedException {
        Object objA = new Object();
        Object objB = new Object();

        new Thread(new MakeLock(objA, objB), "ThreadA").start();
        new Thread(new MakeLock(objB, objA), "ThreadB").start();

        System.out.println("I'm iron man");


    }

    static class MakeLock extends Thread {
        Object objA, objB;

        ReentrantLock lock = new ReentrantLock();
        ReentrantLock lock2 = new ReentrantLock();

        public MakeLock(Object objA, Object objB) {
            this.objA = objA;
            this.objB = objB;
        }
        
        @Override
        public void run() {
            synchronized (objA) {
                System.out.println(Thread.currentThread().getName() + " get an obj");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (objB) {
                    System.out.println(Thread.currentThread().getName() + " get another obj");
                }
            }
        }
    }

}

posted @ 2021-09-30 16:36  klaus08  阅读(167)  评论(0编辑  收藏  举报