Java 生产者消费者 多线程 toys

Main.java

public class Main {

    public static void main(String[] args) {
        Channel channel = new Channel();
        new Thread(new Producer("生产者1", channel)).start();
        new Thread(new Producer("生产者2", channel)).start();
        new Thread(new Customer("消费者1", channel)).start();
    }
}

Channel.java

import java.util.LinkedList;
import java.util.Queue;

/**
 * 消费通道
 * Created by Wiki on 16/1/28.
 */
public class Channel {
    private Queue<Good> goodList = new LinkedList<>();

    public synchronized Good get() {
        if (goodList.size() == 0) {
            return null;
        }
        Good good = goodList.remove();
        return good;
    }

    public synchronized void put(Good good) {
        goodList.add(good);
//        notifyAll();
          notify();
    }
}

Good.java

/**
 * 商品
 * Created by Wiki on 16/1/28.
 */
public class Good {
    private String name;

    public Good(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Produce.java

import java.util.Random;

/**
 * 生产者
 * Created by Wiki on 16/1/28.
 */
public class Producer implements Runnable {
    private static volatile int goodNumber = 0;

    private String name;
    private Channel channel;

    public Producer(String name, Channel channel) {
        this.name = name;
        this.channel = channel;
    }

    @Override
    public void run() {
        while (true) {
            int sleep = new Random().nextInt(2000);
            try {
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Good good = new Good("商品-编号" + (++goodNumber));
            System.out.println(name + " 生产商品:" + good.getName());
            channel.put(good);
        }
    }
}

Consumer.java

/**
 * 消费者
 * Created by Wiki on 16/1/28.
 */
public class Customer implements Runnable {
    private String name;
    private Channel channel;

    public Customer(String name, Channel channel) {
        this.name = name;
        this.channel = channel;
    }

    @Override
    public void run() {
        while (true) {
            Good good = channel.get();
            if (good != null) {
                System.out.println(name + " 获得商品:" + good.getName());
            } else {
                synchronized (channel) {
                    try {
                        System.out.println(name + " 进入等待");
                        channel.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值