1 package com.thread.test.thread;
2
3 /**
4 * Created by windwant on 2016/6/3.
5 */
6 public class MyTestDeadLock {
7 public void run() {
8 MyThread mt = new MyThread();
9 new Thread(mt, "zhangsan").start();
10 new Thread(mt, "lisi").start();
11 }
12
13 class MyThread implements Runnable {
14 private Object o1 = new Object();
15 private Object o2 = new Object();
16 private boolean flag = true;
17
18
19 public void run() {
20 if (flag) {
21 flag = false;
22 synchronized (o1) {
23 System.out.println(Thread.currentThread().getName() + " have o1");
24 try {
25 Thread.sleep(100);
26 } catch (InterruptedException e) {
27 e.printStackTrace();
28 }
29 synchronized (o2) {
30 System.out.println(Thread.currentThread().getName() + " have o2");
31 }
32 }
33 } else {
34 flag = true;
35 synchronized (o2) {
36 System.out.println(Thread.currentThread().getName() + " have o2");
37 try {
38 Thread.sleep(100);
39 } catch (InterruptedException e) {
40 e.printStackTrace();
41 }
42 synchronized (o1) {
43 System.out.println(Thread.currentThread().getName() + " have o1");
44 }
45 }
46 }
47 }
48 }
49
50 public static void main(String[] args) {
51 new MyTestDeadLock().run();
52 }
53 }
项目地址:https://github.com/windwant/threadtest