死锁问题的解决--锁定排序

/**
 * 此类轻易的解决了死锁问题,其核心思想为 各线程按照顺序依次对各对象加锁, 假设有三个线程需要竞争三个资源,线程加锁顺序是
 * lock1,lock2,lock3,这个应该称作为 "资源排序" 4. * 5. * @author Chase 6. * 7.
 */
public class DeadLockSolution {
 private static final Object lock1 = new Object();

 private static final Object lock2 = new Object();

 private static final Object lock3 = new Object();

 private Thread1 thread1 = new Thread1();

 private Thread2 thread2 = new Thread2();

 private Thread3 thread3 = new Thread3();

 class Thread1 extends Thread {
  public void run() {
   synchronized (lock1) {

    System.out.println("线程1已对 1资源 加锁");

    try {

     Thread.sleep(1000);

    } catch (InterruptedException e) {
    }

    synchronized (lock2) {

     System.out.println("线程1已对 2资源 加锁");

     try {

      Thread.sleep(1000);

     } catch (InterruptedException e) {
     }

     synchronized (lock3) {

      System.out.println("线程1已对 3资源 加锁");

      try {

       Thread.sleep(1000);

      } catch (InterruptedException e) {
      }
     }
    }
   }
   System.out.println("线程1运行完毕!");
  }
 }

 class Thread2 extends Thread {
  public void run() {

   synchronized (lock1) {

    System.out.println("线程2已对 1资源 加锁");

    try {

     Thread.sleep(1000);

    } catch (InterruptedException e) {
    }

    synchronized (lock2) {

     System.out.println("线程2已对 2资源 加锁");

     try {

      Thread.sleep(1000);

     } catch (InterruptedException e) {
     }

     synchronized (lock3) {

      System.out.println("线程2已对 3资源 加锁");

      try {

       Thread.sleep(1000);

      } catch (InterruptedException e) {
      }
     }
    }
   }
   System.out.println("线程2运行完毕!");
  }
 }

 class Thread3 extends Thread {
  public void run() {

   synchronized (lock1) {

    System.out.println("线程3已对 1资源 加锁");

    try {

     Thread.sleep(1000);

    } catch (InterruptedException e) {
    }

    synchronized (lock2) {

     System.out.println("线程3已对 2资源 加锁");

     try {

      Thread.sleep(1000);

     } catch (InterruptedException e) {
     }

     synchronized (lock3) {

      System.out.println("线程3已对 3资源 加锁");

      try {

       Thread.sleep(1000);

      } catch (InterruptedException e) {
      }
     }
    }
   }
   System.out.println("线程3运行完毕!");
  }
 }

 public DeadLockSolution() {
  thread1.start();
  thread2.start();
  thread3.start();
 }

 public static void main(String[] args) {
  new DeadLockSolution();
 }
}

/**
 * 2. * 此类轻易的解决了死锁问题,其核心思想为 各线程按照顺序依次对各对象加锁, 3. * 假设有三个线程需要竞争三个资源,线程加锁顺序是
 * lock1,lock2,lock3,这个应该称作为 "资源排序" 4. * 5. * @author Chase 6. * 7.
 */

你可能感兴趣的:(死锁问题的解决--锁定排序)