マルチスレッド_デッドロック
5453 ワード
デッドロック:通常、同期でネストが異なり、ロックが異なります.
1 public class DeadlockDemo {
2 public static void main(String[] args) {
3 Demo d1 = new Demo(true);
4 Demo d2 = new Demo(false);
5
6 Thread t1 = new Thread(d1);
7 Thread t2 = new Thread(d2);
8
9 t1.start();
10 t2.start();
11
12 }
13 }
14 class Demo implements Runnable{
15 private boolean flag;
16 Demo(boolean flag){
17 this.flag = flag;
18 }
19 public void run(){
20 if(flag){
21 synchronized(MyLock.locka){
22 System.out.println("if locka....");
23 synchronized(MyLock.lockb){
24 System.out.println("if lockb....");
25 }
26 }
27 }
28 else{
29 synchronized(MyLock.lockb){
30 System.out.println("else lockb....");
31 synchronized(MyLock.locka){
32 System.out.println("else locka....");
33 }
34 }
35 }
36 }
37 }
38 class MyLock{
39 public static final Object locka = new Object();
40 public static final Object lockb = new Object();
41 }