解决方案 »

  1.   

    /*java 多线程之生产者和消费者模式     效果就生产者生产出一台设备 然后消费者购买走这台设备*/
    public class RunnableCaseDemo03 { public static void main(String[] args) {
    Product pro=new Product();
    Producer3 producer=new Producer3 (pro);
    Consumer3 consumer=new Consumer3 (pro);
    new Thread(producer).start();
    new Thread(consumer).start();
    }
    }
    class Product {

    private String name="Android";
    private String company="Google公司";
    boolean flag=false;
    public synchronized void setInfo (String name,String company){
    if (!flag){
    try{
    super.wait();
    }
    catch (InterruptedException e){
    e.printStackTrace();
    }
    }
    /*就是下面的这四行我打算用else {}框起来的  但是就是得不到我要的效果了  请大家帮忙看看*/
    this.setName(name);
    this.setCompany(company);
    flag=false;
    super.notify();


    }
    public synchronized void getInfo (){
    if (flag){
    try{
    super.wait();
    }
    catch (InterruptedException e){
    e.printStackTrace ();
    }
    }

    System.out.println(this.getName()+"-->"+this.getCompany());
    flag=true;
    super.notify();
    }
    public void setName (String name){
    this.name=name;
    }
    public void setCompany(String company){
    this.company=company;
    }
    public String getName(){
    return this.name;
    }
    public String getCompany(){
    return this.company;
    }
    }
    class Producer3 implements Runnable{
    private Product pro=null;
    public Producer3 (Product pro){
    this.pro=pro;
    }
    boolean flag=false;
    public void run (){
    for (int i=0;i<10;i++){
    if (flag){
    this.pro.setInfo("Android", "Google公司");
    flag=false;
    }
    else{
    this.pro.setInfo("Ios", "Appel公司");
    flag=true;
    }
    }
    }

    class Consumer3 implements Runnable{
    private Product pro=null;
    public Consumer3 (Product pro){
    this.pro=pro;
    }
    public void run (){
    for (int i=0;i<10;i++){
    this.pro.getInfo();
    }
    }
    }