ReentrantLock替换synchronized解决多线程并发死锁,Java
Posted zhangphil
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 运行结束
以上是关于ReentrantLock替换synchronized解决多线程并发死锁,Java的主要内容,如果未能解决你的问题,请参考以下文章
ReentrantLock替换synchronized解决多线程并发死锁,Java