手写死锁&&死锁的原因是什么?如何快速定位死锁?如何避免死锁

一个简单的死锁案例:

package mylock;

public class DeadlockExample {
    public static void main(String[] args) {
        final Object resource1 = new Object();
        final Object resource2 = new Object();

        // 线程1占用资源1,等待资源2
        Thread thread1 = new Thread(() -> {
            synchronized (resource1){
                System.out.println("Thread 1: 持有资源 1");

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

                synchronized (resource2){
                    System.out.println("Thread 1: 持有资源 2");
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (resource2){
                System.out.println("Thread 2: 持有资源 2");

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

                synchronized (resource1){
                    System.out.println("Thread 2: 持有资源 1");
                }
            }
        });

        thread1.start();
        thread2.start();
    }


}

转载:https://www.bilibili.com/video/BV1Ts4y1z7mv/?spm_id_from=333.337.top_right_bar_window_history.content.click&vd_source=46d50b5d646b50dcb2a208d3946b1598

posted @ 2023-07-17 10:49  Chenyi_li  阅读(21)  评论(0)    收藏  举报