e_webapp 2012-04-27 17:44 采纳率: 0%
浏览 274
已采纳

Java多线程,生产消费问题

package thread;

public class Producer_ConsumerTest {
public static void main(String[] args) {
SyncStack ss = new SyncStack();
Thread producter = new Producter(ss);
Thread consumer = new Consumer(ss);
producter.start();
consumer.start();
}
}
class SyncStack {
private int total = 0;
private boolean flag = false;
synchronized void product() {
while(flag == true) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
total++;
flag = true;
this.notify();
}
synchronized int conmuse() {
while(flag == false) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
total--;
flag = false;
this.notify();
return total;
}
}
class Producter extends Thread {
SyncStack ss;
Producter(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=1;i<10;i++) {
ss.product();
System.out.println("生产者" + Thread.currentThread().getName() + "生产了第" + i + "个商品,商品总数为");
}
}
}
class Consumer extends Thread {
SyncStack ss;
Consumer(SyncStack ss) {
this.ss = ss;
}
public void run() {
for(int i=1;i<10;i++) {
ss.conmuse();
System.out.println("消费者" + Thread.currentThread().getName() + "消费了第" + i + "个商品总数为");
}
}

}

[b]我希望的输出结果是生产1个,然后消费1个,生产在前,但是达不到要求,目前实际输出是无序的,哪位朋友能帮忙修改一下吗?[/b]

  • 写回答

3条回答 默认 最新

  • lc250846434 2012-04-27 21:18
    关注

    额。。
    发现一个问题
    this.notify();
    加在a()方法里面,return上面。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格