1 public class DeadLock3 implements Runnable {
 2     
 3     private static Object obj1 = new Object();
 4     private static Object obj2 = new Object();
 5 
 6     @Override
 7     public void run() {
 8         System.out.println("Current Thread: " + Thread.currentThread().getName());
 9         for (int i = 1; i < 3; i++) {
10             System.out.println("i: " + i);
11             if (i % 2 != 0) {
12                 //odd
13                 System.out.println("Lock object1 first then lock object2");
14                 synchronized (obj1) {
15                     try {
16                         Thread.sleep(500);
17                     } catch (InterruptedException e) {
18                         e.printStackTrace();
19                     }
20                     synchronized (obj2) {}
21                 }
22             } else {
23                 //even
24                 System.out.println("Lock object2 first then lock object1");
25                 synchronized (obj2) {
26                     try {
27                         Thread.sleep(500);
28                     } catch (InterruptedException e) {
29                         e.printStackTrace();
30                     }
31                     synchronized (obj1) {}
32                 }
33             }
34         }
35     }
36 
37     public static void main(String[] args) {
38         new Thread(new DeadLock3()).start();
39         new Thread(new DeadLock3()).start();
40     }
41 }
View Code

相关文章: