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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈文杰 中级黑马   /  2013-11-21 01:56  /  1373 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

怎么解决死锁呀


package com.app.thread;

import javax.swing.plaf.SliderUI;

public class LockDemo {
public static void main(String[] args) {
//  System.out.println("lock");

  final OutTurn ot = new OutTurn();
  
  for(int j=0;j<100;j++){

   new Thread(new Runnable() {

    public void run() {
//     try {
//      Thread.sleep(10);
//     } catch (InterruptedException e) {
//      e.printStackTrace();
//     }
     for (int i = 0; i <5; i++) {     
      ot.sub();
     }
    }
   }).start();

   new Thread(new Runnable() {

    public void run() {
//     try {
//      Thread.sleep(10);
//     } catch (InterruptedException e) {
//      e.printStackTrace();
//     }
     for (int i = 0; i < 5; i++) {     
      ot.main();
     }
    }
   }).start();
  }

}
}

class OutTurn {
private boolean isSub = true;
private int count=0;

public synchronized void sub() {
  try {
   while (!isSub) {
    this.wait();
   }
   System.out.println("sub ---- "+count);
   isSub=false;
   this.notify();
  } catch (Exception e) {
   e.printStackTrace();
  }
  count++;

}

public synchronized void main() {
  try {
   while(isSub){
    this.wait();
   }
   System.out.println("main (((((((((((( "+count);
   isSub=true;
   this.notify();
  } catch (Exception e) {
   e.printStackTrace();
  }
  count++;
}
}

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

4 个回复

倒序浏览
notifyAll就行了
回复 使用道具 举报
而且你这个不是死锁,死锁是锁中嵌套锁,你这个是由于线程都在那等待了,虽然你创建了内部类,但是实际上你的内部类被多次调用,等于就是创建多个线程来运行sub和main方法,跟毕老师视频上的创建多个线程操作生产者消费者道理差不多,所以应该全部唤醒,notifyAll。
回复 使用道具 举报
你那一个创建线程前面的for(100)就等于new了100个thread,你说你不用notifyAll可能么。。。
回复 使用道具 举报
我擦  我25分了,哈哈哈哈  回答问题的日子终于过去了!!!!!!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马