你把 notify 换成 notifyAll 就行了,前者是唤醒一个线程,后者唤醒所有线程
解决方案 »
- 求救:程序中取连接池的当前连接数(在线等)
- Java中String.replace()时的正则表达式不会写了, :(
- 最后几题。。。。。。谢谢了。。
- list判断重复值的问题!请大家帮忙!
- 关于assertion的题
- Applet中和JApplet中createImage(int, int)的区别
- 写个HELLO WORD!!JDK都报错,对JAVA的热情都浇灭了。
- 给个自解压jar文件的代码给大家,我教学生的代码之一,排版不好,大家拷贝到eclipse即用
- 有关Java Swing的图形界面编程的问题,高手请进!
- 关于replaceFirst的问题
- 刚才发现了一件颠覆我三观的问题
- 子类为什么可以覆写父类的方法?
我为了用notify() 在等待前就notify()一次啊,为的是防止死锁,但是这样防止死锁了,却唤不醒对方了,结果有两个线程在死循环里了
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("no args.");
}
}
}像楼主的代码层级多,又没有排版,没法看。
private String name;
private int count = 0;
private boolean flag = false; public synchronized void set(String name) {
/*while (flag) {
notify();
try {
wait();
} catch (InterruptedException e) {
}
System.out
.println(Thread.currentThread().getName() + "....循环唤醒..."); }*/
if(count > 0){
notifyAll();
}
count++;
this.name = name;
System.out.println(Thread.currentThread().getName() + "....生产者..."
+ this.name + ":" + count);
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
//flag = true;
//notify(); } public synchronized void out() {
/*while (!flag) {
notify();
try {
wait();
} catch (InterruptedException e) {
}
System.out
.println(Thread.currentThread().getName() + "....循环唤醒..."); }*/
if(count < 1){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
count--;
//this.name = name + count;
System.out.println(Thread.currentThread().getName() + "....消费者......."
+ this.name + ":" + count);
//flag = false;
notifyAll();
}}class Producer implements Runnable {
Resource r; Producer(Resource r) {
this.r = r;
} public void run() {
//while (true)
r.set("烤鸭"); }
}class Consumer implements Runnable {
Resource r; Consumer(Resource r) {
this.r = r;
} public void run() {
//while (true)
r.out();
}
}public class ProducerConsumerDemo {
public static void main(String[] args) {
Resource r = new Resource(); Producer p = new Producer(r);
Consumer c = new Consumer(r);
Thread t1 = new Thread(p,"p1");
Thread t2 = new Thread(p,"p2");
Thread t3 = new Thread(c,"c1");
Thread t4 = new Thread(c,"c2");
t1.start();
t2.start();
t3.start();
t4.start();
}
}