- 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 运行结束