Loading

[Java手撕]手撕死锁

一种不安全的写法

public class Main {

    public static final Object lock1 = new Object();
    public static final Object lock2 = new Object();

    public static void main(String[] args) {

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock1) {
                    System.out.println(Thread.currentThread().getName() + "已经获取了lock1");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    synchronized (lock2) {
                        System.out.println(Thread.currentThread().getName() + "已经获取了lock2");
                    }
                }
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock2) {
                    System.out.println(Thread.currentThread().getName() + "已经获取了lock2");
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    synchronized (lock1) {
                        System.out.println(Thread.currentThread().getName() + "已经获取了lock1");
                    }
                }
            }
        });

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

一种安全的写法

import java.io.*;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

public class Main {

    public static final ReentrantLock lock1 = new ReentrantLock();
    public static final ReentrantLock lock2 = new ReentrantLock();

    public static void main(String[] args) {

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    // 尝试获取 lock1,等待2秒
                    if (lock1.tryLock(2, TimeUnit.SECONDS)) {
                        try {
                            System.out.println("Thread1: Holding lock1...");
                            // 尝试获取 lock2,等待2秒
                            if (lock2.tryLock(2, TimeUnit.SECONDS)) {
                                try {
                                    System.out.println("Thread1: Holding lock1 & lock2...");
                                    // Critical section
                                } finally {
                                    lock2.unlock();
                                }
                            } else {
                                System.out.println("Thread1: Could not acquire lock2, releasing lock1...");
                            }
                        } finally {
                            lock1.unlock();
                            System.out.println("Thread1: releasing lock1...");
                        }
                    } else {
                        System.out.println("Thread1: Could not acquire lock1...");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    // 尝试获取 lock2,等待2秒
                    if (lock2.tryLock(2, TimeUnit.SECONDS)) {
                        try {
                            System.out.println("Thread2: Holding lock2...");
                            // 尝试获取 lock1,等待2秒
                            if (lock1.tryLock(2, TimeUnit.SECONDS)) {
                                try {
                                    System.out.println("Thread2: Holding lock2 & lock1...");
                                    // Critical section
                                } finally {
                                    lock1.unlock();
                                }
                            } else {
                                System.out.println("Thread2: Could not acquire lock1, releasing lock2...");
                            }
                        } finally {
                            lock2.unlock();
                            System.out.println("Thread2: releasing lock2...");
                        }
                    } else {
                        System.out.println("Thread2: Could not acquire lock2...");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });

        thread1.start();
        thread2.start();
    }
}
posted @   Duancf  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示