看看是什么,这是我自己写的
- import java.util.concurrent.locks.*;
- public class DeadLockTest {
- public static void main(String[] args) {
- Lock locka = new ReentrantLock();
- Lock lockb = new ReentrantLock();
- DeadLock1 lock1 = new DeadLock1(locka, lockb);
- DeadLock2 lock2 = new DeadLock2(locka, lockb);
- new Thread(lock1).start();
- new Thread(lock2).start();
- }
- }
- class DeadLock1 implements Runnable {
- Lock locka;
- Lock lockb;
- public DeadLock1(Lock a, Lock b) {
- locka = a;
- lockb = b;
- }
- @Override
- public void run() {
- locka.lock();
- try {
- System.out.println(Thread.currentThread().getName() + ":" + "获得locka");
- Thread.sleep(1000);
- lockb.lock();
- System.out.println(Thread.currentThread().getName() + ":" + "获得lockb");
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- lockb.unlock();
- locka.lock();
- }
- }
- }
- class DeadLock2 implements Runnable {
- Lock locka;
- Lock lockb;
- public DeadLock2(Lock a, Lock b) {
- locka = a;
- lockb = b;
- }
- @Override
- public void run() {
- lockb.lock();
- try {
- System.out.println(Thread.currentThread().getName() + ":" + "获得lockb");
- Thread.sleep(1000);
- locka.lock();
- System.out.println(Thread.currentThread().getName() + ":" + "获得locka");
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- locka.unlock();
- lockb.lock();
- }
- }
- }
复制代码 |