A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© liuhao_hm 中级黑马   /  2015-7-12 22:34  /  420 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. class Test implements Runnable
  2. {
  3.         private boolean flag;
  4.         Test(boolean flag)
  5.         {
  6.                 this.flag = flag;
  7.         }
  8.         public void run()
  9.         {
  10.                 if(flag)
  11.                 {
  12.                         while(true)
  13.                         {
  14.                                 synchronized(MyLock.locka)
  15.                                 {
  16.                                         System.out.println(Thread.currentThread().getName()+"if...");
  17.                                 }
  18.                                         synchronized(MyLock.lockb)
  19.                                         {
  20.                                                 System.out.println(Thread.currentThread().getName()+"if...");
  21.                                         }
  22.                         }
  23.                 }
  24.                 else
  25.                 {
  26.                         while(true)
  27.                         {
  28.                                 synchronized(MyLock.lockb)
  29.                                 {
  30.                                         System.out.println(Thread.currentThread().getName()+"else...");
  31.                                 }
  32.                                         synchronized(MyLock.locka)
  33.                                         {
  34.                                                 System.out.println(Thread.currentThread().getName()+"else...");
  35.                                         }
  36.                         }
  37.                 }
  38.         }
  39. }
  40. class MyLock
  41. {
  42.         public static final Object locka = new Object();
  43.         public static final Object lockb = new Object();
  44. }

  45. class DeadlockDemo
  46. {
  47.         public static void main(String[] args)
  48.         {
  49.                 Test a = new Test(true);
  50.                 Test b = new Test(false);
  51.                 Thread t1 = new Thread(a);
  52.                 Thread t2 = new Thread(b);
  53.                 t1.start();
  54.                 t2.start();

  55.         }
  56. }
复制代码

1 个回复

倒序浏览
长知识了。。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马