线程通信问题分解1

package com.msb.test10;

/**
 * @author : liu
 * 日期:15:42:06
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class Product {//商品类
    //品牌
    private String brand;
    //名字
    private String name;
    //setter,getter方法:
    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.msb.test10;

/**
 * @author : liu
 * 日期:15:45:09
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class ProducerThread extends Thread{//生产者线程
    //共享商品
    private Product p;

    public ProducerThread(Product p) {
        this.p = p;
    }
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {//生产十个商品
            if(i%2==0){
                //生产费列罗巧克力
                p.setBrand("费列罗");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                p.setName("巧克力");
            }else{
                p.setBrand("哈尔滨");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                p.setName("啤酒");
            }
            System.out.println("生产者生产了:"+p.getBrand() + "---"+ p.getName());
        }
    }
}
package com.msb.test10;

import com.sun.media.sound.RIFFInvalidDataException;

/**
 * @author : liu
 * 日期:16:02:52
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class CustomerThread extends Thread{//消费者线程
    //共享商品资源
    private Product p;

    public CustomerThread(Product p) {
        this.p = p;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10 ; i++) {//消费次数
            System.out.println("消费者消费了:"+ p.getBrand()+"---"+ p.getName());
        }
    }
}
package com.msb.test10;

/**
 * @author : liu
 * 日期:16:07:36
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class Test {
    //这是一个main方法:是程序的入口
    public static void main(String[] args) {
        //共享商品
        Product p=new Product();
        ProducerThread pt=new ProducerThread(p);
        CustomerThread ct=new CustomerThread(p);
        pt.start();
        ct.start();
    }
}

 

出现问题:

1.生产者和消费者么有交替输出

2.打印数据错乱

费列罗啤酒

哈尔滨巧克力

posted @ 2022-12-23 16:31  爱的加勒比  阅读(15)  评论(0)    收藏  举报