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

Java学习-死锁练习

时间:2020-01-27 15:18:13      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:box   inter   new   线程   tar   void   cat   sync   col   

3个同步对象a, b, c
3个线程 t1,t2,t3
故意设计场景,使这3个线程彼此死锁

 1 package multiplethread;
 2 
 3 import charactor.Hero;
 4 
 5 public class Test5 {
 6     public static void main(String[] args) {
 7           Hero a=new Hero("a");
 8           Hero b=new Hero("b");
 9           Hero c=new Hero("c");
10           Thread t1=new Thread(){
11               public void run(){
12                   synchronized (a) {
13                     System.out.println("t1已经占有a");
14                     try {
15                         Thread.sleep(1000);
16                     } catch (InterruptedException e) {
17                         // TODO Auto-generated catch block
18                         e.printStackTrace();
19                     }
20                     System.out.println("t1试图占有b");
21                     synchronized (b) {
22                         System.out.println("占有成功");
23                     }
24                 }
25               }
26           };
27           t1.start();
28           Thread t2=new Thread(){
29               public void run(){
30                   synchronized (b) {
31                     System.out.println("t2已经占有b");
32                     try {
33                         Thread.sleep(1000);
34                     } catch (InterruptedException e) {
35                         // TODO Auto-generated catch block
36                         e.printStackTrace();
37                     }
38                     System.out.println("t2试图占有c");
39                     synchronized (c) {
40                         System.out.println("占有成功");
41                     }
42                 }
43               }
44           };
45           t2.start();
46           Thread t3=new Thread(){
47               public void run(){
48                   synchronized (c) {
49                     System.out.println("t3已经占有c");
50                     try {
51                         Thread.sleep(1000);
52                     } catch (InterruptedException e) {
53                         // TODO Auto-generated catch block
54                         e.printStackTrace();
55                     }
56                     System.out.println("t3试图占有a");
57                     synchronized (a) {
58                         System.out.println("占有成功");
59                     }
60                 }
61               }
62           };
63           t3.start();
64     }
65 }

效果图:

技术图片

 

Java学习-死锁练习

标签:box   inter   new   线程   tar   void   cat   sync   col   

原文地址:https://www.cnblogs.com/gilgamesh-hjb/p/12236044.html

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