Java 生产者消费者 多线程 toys

来源:互联网 发布:淘宝客服礼貌用语 编辑:程序博客网 时间:2024/05/19 01:14

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();                    }                }            }        }    }}
0 0
原创粉丝点击