黑马程序员技术交流社区
标题:
死锁
[打印本页]
作者:
陈文杰
时间:
2013-11-21 01:56
标题:
死锁
怎么解决死锁呀
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++;
}
}
作者:
hubby
时间:
2013-11-21 09:39
notifyAll就行了
作者:
hubby
时间:
2013-11-21 09:44
而且你这个不是死锁,死锁是锁中嵌套锁,你这个是由于线程都在那等待了,虽然你创建了内部类,但是实际上你的内部类被多次调用,等于就是创建多个线程来运行sub和main方法,跟毕老师视频上的创建多个线程操作生产者消费者道理差不多,所以应该全部唤醒,notifyAll。
作者:
hubby
时间:
2013-11-21 09:46
你那一个创建线程前面的for(100)就等于new了100个thread,你说你不用notifyAll可能么。。。
作者:
hubby
时间:
2013-11-21 09:51
我擦 我25分了,哈哈哈哈 回答问题的日子终于过去了!!!!!!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2