java实现生产者消费者问题,求大神看看哪里的问题

wjw19940424 2015-04-27 12:36:49
package entity;
public class Apple {
public Integer num = 0;
public void addApple() {
synchronized (num) {
while (num == 5) {
try {
num.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num++;
System.out.println(Thread.currentThread().getName() + "添加苹果" + " "
+ "苹果数量" + num);
num.notifyAll();
}
}
public void getApple() {
synchronized (num) {
while (num == 0) {
try {
num.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num--;
System.out.println(Thread.currentThread().getName() + "取走苹果" + " "
+ "苹果数量" + num);
num.notifyAll();
}
}

}

package xiancheng;

import entity.Apple;

public class Add implements Runnable {

public Apple apple;

public Add(){}

public Add(Apple apple){
this.apple=apple;
}



@Override
public void run() {
// TODO Auto-generated method stub

apple.addApple();


}

}

package xiancheng;

import entity.Apple;

public class Min implements Runnable {

public Apple apple;

public Min(){}

public Min(Apple apple){
this.apple=apple;
}

@Override
public void run() {
// TODO Auto-generated method stub


apple.getApple();

}

}

package xiancheng;

import entity.Apple;

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Apple apple = new Apple();
Add add = new Add(apple);
Min min = new Min(apple);

new Thread(add).start();
new Thread(add).start();
new Thread(add).start();
new Thread(add).start();
new Thread(add).start();
new Thread(min).start();
new Thread(min).start();
new Thread(min).start();
new Thread(min).start();
new Thread(min).start();

}

}

...全文
100 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
姜小白- 2015-04-27
  • 打赏
  • 举报
回复
将num.wait() 修改为
this.wait();//让当前线程等待
oh_Maxy 2015-04-27
  • 打赏
  • 举报
回复
2L说的对,1L的方法会产生死锁。 可以改进下,自定义一个MyInteger类,里面只有一个int num=0, public Integer num = 0; 改成 public MyInteger myNum = 0; 对num的锁定操作改成对myNum的锁定,这样试试吧
Chengyajie521 2015-04-27
  • 打赏
  • 举报
回复
下面是源码中对notify的解释,认真看一下,notify中的对象必须是这个线程的监视者,成为监视者可以有3中方法,下面有详细 * This method should only be called by a thread that is the owner * of this object's monitor. A thread becomes the owner of the * object's monitor in one of three ways: * 1.By executing a synchronized instance method of that object. * 2.By executing the body of a {@code synchronized} statement * that synchronizes on the object. * 3.For objects of type {@code Class,} by executing a * synchronized static method of that class. 明显这个线程的监视对象是num,但是 Integer++以后变成了新的对象,比如说你再synchronize块中锁的是num对象,然后你把num++了,他变成了另一个对象(新的地址),所以他已经不是这个线程的监视者了

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧