Java 写一个生产者和消费者的多线程Demo
/** * 文件名: Customer.java * * 顾客 * **/ public class Customer{ @SuppressWarnings("unused") private Shop shop = null; private String name = null; public void buy(){ int count = shop.getBreadCount(); if(count > 0){ shop.setBreadCount(--count); System.out.println(name +" says : I bought a bread, now the remained quantity is : "+ count +"!"); }else { System.out.println(name + " says : What a pity, there is no bread left!----------------------"); } } public Customer(Shop shop, String name){ this.shop = shop; this.name =name; } }
/** * 文件名: CustomerGenerator.java * * 顾客生成器 * **/ public class CustomerGenerator extends Thread { private Shop shop = null; public CustomerGenerator(Shop shop){ this.shop = shop; } public void run() { Customer customer = null; int count = 1; while(shop.isOpen()){ customer = new Customer(shop, count+"顾客"); customer.buy(); customer = null; count++; try { Thread.sleep(600); } catch (InterruptedException e) { e.printStackTrace(); } } } }
/** * 文件名: Producer.java * * 生产者 * **/ public class Producer extends Thread { @SuppressWarnings("unused") private Shop shop = null; private String name = null; public void produce(){ int count = shop.getBreadCount(); shop.setBreadCount(++count); System.out.println(Thread.currentThread().getName()+" says : I produced a bread, now the count is : "+ count); } public Producer(Shop shop, String name){ this.shop = shop; super.setName(name); } public void run() { Random random = new Random(); while(shop.isOpen()){ this.produce(); try { int speed = 1500 + random.nextInt(1000); Thread.sleep(speed);//生产面包的速度 } catch (InterruptedException e) { e.printStackTrace(); } } } }
/** * 文件名: Shop.java * * 面包店 * **/ public class Shop { private int breadCount = 0;//当前面包店剩余的面包数量 private boolean isOpen = true;//是否正在营业 public synchronized int getBreadCount() { return breadCount; } public synchronized void setBreadCount(int breadCount) { this.breadCount = breadCount; } public boolean isOpen() { return isOpen; } public void setOpen(boolean isOpen) { this.isOpen = isOpen; } }
** * 文件名: ShopManager.java * * 生产消费者管理 * **/ public class ShopManager { public static void main(String[] args) { Shop shop = new Shop(); Producer pc1 = new Producer(shop, "1#面点师"); Producer pc2 = new Producer(shop, "2#面点师"); Producer pc3 = new Producer(shop, "3#面点师"); CustomerGenerator customerGenerator = new CustomerGenerator(shop); pc1.start(); pc2.start(); pc3.start(); customerGenerator.start(); try { Thread.sleep(30000);//工作时间 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("I' m sorry, 下班啦..."); shop.setOpen(false); } }