ReentrantLock替换synchronized解决多线程并发死锁,Java

ReentrantLock替换synchronized解决多线程并发死锁,Java

import java.util.concurrent.locks.ReentrantLock;

public class MainClass {
    private ReentrantLock lock1 = new ReentrantLock();

    private ReentrantLock lock2 = new ReentrantLock();


    public static void main(String[] args) {
        MainClass mainClass = new MainClass();
        mainClass.demo();
    }

    private void demo() {
        Thread ta = new Thread(new DeadA());
        Thread tb = new Thread(new DeadB());
        ta.start();
        tb.start();
    }

    private class DeadA implements Runnable {
        private String id = "A";

        @Override
        public void run() {
            System.out.println(id + " 申请锁1...");
            lock1.lock();
            System.out.println(id + " 获得锁1");
            lock1.unlock();

            System.out.println(id + " 申请锁2...");
            lock2.lock();
            System.out.println(id + " 获得锁2");
            lock2.unlock();

            System.out.println(id + " 运行结束");
        }
    }

    private class DeadB implements Runnable {
        private String id = "B";

        @Override
        public void run() {
            System.out.println(id + " 申请锁2...");
            lock2.lock();
            System.out.println(id + " 获得锁2");
            lock2.unlock();

            System.out.println(id + " 申请锁1...");
            lock1.lock();
            System.out.println(id + " 获得锁1");
            lock1.unlock();

            System.out.println(id + " 运行结束");
        }
    }
}

输出:

A 申请锁1...
B 申请锁2...
B 获得锁2
A 获得锁1
B 申请锁1...
B 获得锁1
A 申请锁2...
B 运行结束
A 获得锁2
A 运行结束

Java多线程并发环境下的synchronized死锁实例_zhangphil的博客-CSDN博客Java并发多线程环境中,造成死锁的最简单的场景是:多线程中的一个线程T_A持有锁L1并且申请试图获得锁L2,而多线程中另外一个线程T_B持有锁L2并且试图申请获得锁L1。线程的锁申请操作是阻塞的,于是造成线程T_A和线程T_B无法正确获得想要的锁,两个线程被阻塞进入死锁状态。https://blog.csdn.net/zhangphil/article/details/127534524

Java线程同步可重入锁ReentrantLock与Condition_zhangphil的博客-CSDN博客import java.util.LinkedList;import java.util.Queue;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class Main { private Queue...https://blog.csdn.net/zhangphil/article/details/92814997

Java线程同步锁ReentrantLock和Condition中断等待程序前提条件满足_zhangphil的博客-CSDN博客import java.util.concurrent.TimeUnit;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;/** * ReentrantLock的lock和unlock必须成对使用且把需要同步的代码块包裹起来。 * lock-unlo...https://blog.csdn.net/zhangphil/article/details/92826986

你可能感兴趣的:(多线程,Java,java,多线程)