码迷,mamicode.com
首页 > 编程语言 > 详细

线程死锁示例

时间:2018-01-04 14:24:53      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:super   end   dex   span   over   run   pack   ram   代码   

线程死锁:

 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 }

 

线程死锁示例

标签:super   end   dex   span   over   run   pack   ram   代码   

原文地址:https://www.cnblogs.com/enjoyjava/p/8192661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!