weixin_42237606 2018-09-13 07:55 采纳率: 0%
浏览 407

初学者---多线程同步问题---消费者线程似乎并没有调用notify()方法,生产者就被唤醒了?

图片说明

附程序如下:

package TestThread1;

/**

  • Mission : 设计一个生产电脑 和搬运电脑类,要求生产出一台电脑就搬走一台,如果没有新的电脑产出,则要等待新的电脑产出;如果产出的电脑没有搬走
  • 则要等待电脑搬走之后再生产,并统计出生产的电脑数量。
  • @author Administrator * */

public class ThreadDemo10 {
public static void main(String[] args) {
Resource res=new Resource();
new Thread(new Producer(res)).start();
new Thread(new Consumer(res)).start();
}
}

class Producer implements Runnable{
private Resource resource;
public Producer(Resource resource) {
this.resource=resource;
};
public void run() {
for(int x=0;x<50;x++) {
try {
this.resource.make();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

    }
}

}
class Consumer implements Runnable{
private Resource resource;
public Consumer(Resource resource) {
this.resource=resource;
};
public void run() {
for(int x=0;x<50;x++) {
try {
this.resource.get();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

    }
}

}

class Resource {
private int in=0;
private Computer computer;
public synchronized void make() throws Exception{

    if(this.computer!=null) {
        super.wait();
    }else {
    Thread.sleep(100);
    this.computer=new Computer("MLDB牌电脑",1.1);
    System.out.println("生成一台电脑"+this.computer);
    System.out.println("制造者唤醒其他线程");
    super.notifyAll();
}

    }
public synchronized void get() throws Exception {
    System.out.println("进入 get()");
    if(this.computer==null) {  //没有生产过
        in++;
         Thread.currentThread().setName("制造者AAAAAAAAAAAAAAAAAAA"+" "+in);
         System.out.println(Thread.currentThread().getName() + " 阻塞");
            super.wait();
    }
    else {
        System.out.println("被Producer线程唤醒,已经可以取电脑了");
    try {
        Thread.sleep(10);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("取走电脑"+this.computer);
    this.computer=null;
    super.notify();     
}
System.out.println("从wait()之后开始执行,因为已经执行了if,故不会执行else.----此处表明等待中的线程是由wait之后开始执行");
}

}

class Computer{
private static int count=0; //表示生产的个数
private String name;
private double price;
public Computer (String name ,double price) {
this.name=name;
this.price=price;
count++;
}
public String toString() {
return "【第"+count+"台电脑】"+"电脑名字 "+this.name+"、价值."+this.price;
}
}

  • 写回答

1条回答 默认 最新

  • 瓦史托德 2018-09-13 10:17
    关注

    if判断computer的改成while

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算