线程死锁示例

线程死锁:

 1 package com.iotek.synchronizedtest;
 2 
 3 public class DeadThread {
 4 
 5     /**
 6      * 线程死锁示例
 7      * 相互等待锁的释放,导致死锁,应避免同步块里面出现锁的嵌套!!!
 8      * @param args
 9      */
10     public static void main(String[] args) {
11         Example example = new Example();
12         DieThread1 thread1 = new DieThread1(example);
13         thread1.start();
14         DieThread2 thread2 = new DieThread2(example);
15         thread2.start();
16         
17     }
18 
19 }
20 
21 class DieThread1 extends Thread {
22     private Example example = null;
23 
24     public DieThread1(Example example) {
25         super();
26         this.example = example;
27     }
28 
29     @Override
30     public void run() {
31         example.method1();
32     }
33 }
34 
35 class DieThread2 extends Thread {
36     private Example example = null;
37 
38     public DieThread2(Example example) {
39         super();
40         this.example = example;
41     }
42 
43     @Override
44     public void run() {
45         example.method2();
46     }
47 }
48 
49 class Example {
50     private Object obj1 = new Object();
51     private Object obj2 = new Object();
52 
53     public void method1() {
54         synchronized (obj1) {
55             // 同步代码块,获取对象obj1的锁
56             try {
57                 Thread.sleep(1000); // 线程等待
58             } catch (InterruptedException e) {
59                 e.printStackTrace();
60             }
61             synchronized (obj2) {
62                 // 获取对象obj1的锁的同时,获取obj2的锁
63                 System.out.println("method1");
64             }
65         }
66     }
67 
68     public void method2() {
69         synchronized (obj2) {
70             // 同步代码块,获取对象obj2的锁
71             try {
72                 Thread.sleep(1000); // 线程等待
73             } catch (InterruptedException e) {
74                 e.printStackTrace();
75             }
76             synchronized (obj1) {
77                 // 获取对象obj2的锁的同时,获取obj1的锁
78                 System.out.println("method2");
79             }
80         }
81     }
82 
83 }

 

posted @ 2018-01-04 13:03  清风拂来  阅读(290)  评论(0编辑  收藏  举报