奥特曼打怪兽

打怪升级,过关斩将

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
 1 package ;
 2 
 3 /**
 4  * 死锁的四大条件 条件互斥 形成环路 循环等待 请求保持条件
 5  *
 6  * 避免死锁的方法:获取2把锁之前睡眠时间差越大,理论上会缓解一点. 死锁不能消除,只能避免或缓解
 7  * (1) 互斥条件:一个资源每次只能被一个进程使用。
 8 (2) 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
 9 (3) 不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。
10 (4) 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。
11 这四个条件是死锁的必要条件,只要系统发生死锁,这些条件必然成立,而只要上述条件之
12 一不满足,就不会发生死锁。
13  *
14  */
15 
16 public class DeadLock extends Thread {
17     String s1 = "hello";
18     String s2 = "world";
19     int i = 0;
20 
21     public static void main(String[] args) {
22         DeadLock d = new DeadLock();
23         DeadLock d1 = new DeadLock();
24         d.i = 1;
25         d1.i = 2;
26         d.start();
27         d1.start();
28     }
29 
30     public void run() {
31         while (i == 1) {
32             synchronized (s1) {
33                 System.out.println(Thread.currentThread() + "first lock");
34                 synchronized (s2) {
35                     System.out.println(Thread.currentThread() + "second lock");
36                 }
37             }
38         }
39 
40         while (i == 2) {
41             synchronized (s2) {
42                 System.out.println(Thread.currentThread() + "second lock");
43                 synchronized (s1) {
44                     System.out.println(Thread.currentThread() + "first lock");
45                 }
46             }
47         }
48     }
49 
50 }

 

posted on 2017-03-15 19:53  奥特曼打怪兽  阅读(143)  评论(0编辑  收藏  举报