Java 死锁问题

 1 package demo09;
 2 
 3 //进程死锁
 4 public class DeadLockThread implements Runnable {
 5     static Object a = new Object();
 6     static Object b = new Object();
 7     private boolean flag;
 8     DeadLockThread(boolean flag) {
 9         this.flag = flag;
10     }
11     
12     public void run() {
13         if (flag) {
14             while (true) {
15                 //a锁对象上的同步代码块
16                 synchronized (a) {
17                     System.out.println(Thread.currentThread().getName()+"a...");
18                     //b锁对象上的同步代码块
19                     synchronized (b) {
20                         System.out.println(Thread.currentThread().getName()+"b...");
21                     }
22                 }
23             }
24         } else {
25             while (true) {
26                 //b锁对象上的同步代码块
27                 synchronized (b) {
28                     System.out.println(Thread.currentThread().getName()+"b...");
29                     //a锁对象上的同步代码块
30                     synchronized (a) {
31                         System.out.println(Thread.currentThread().getName()+"a...");
32                     }
33                 }
34             }
35         }
36     }
37     
38 }
 1 package demo09;
 2 
 3 public class LockDemo {
 4     public static void main(String[] args) {
 5         DeadLockThread d1 = new DeadLockThread(true);
 6         DeadLockThread d2 = new DeadLockThread(false);
 7         
 8         //创建并开启两个线程
 9         new Thread(d1, "线程1").start();
10         new Thread(d2, "线程2").start();
11     }
12 }

 

    原文作者:对影007
    原文地址: https://www.cnblogs.com/lwn007/p/6933910.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞