1. 程式人生 > >多線程簡單實例(2)生產者和消費者

多線程簡單實例(2)生產者和消費者

interrupt block eas zed rgs .get () oid nal

這是一個生產者和消費者的例子。消費者從倉庫取物品,生產者向倉庫增加商品。

當商品說達到最大時,不能繼續增加商品,應該通知其他線程去取商品。

同樣,當倉庫商品為空時,無法取商品,而是通知其他線程增加商品。

這裏用到線程的兩個常用的方法:notifyAll和wait方法。

package code.thread;
//Product and Custom
public class ProAndCus {
    public static void main(String[] args) {
        Store store = new Store(10);
        Custom custom 
= new Custom(store); Product product = new Product(store); Custom custom2 = new Custom(store); Product product2 = new Product(store); custom.start(); product.start(); custom2.start(); product2.start(); } } //商品倉庫 class Store { //最大儲存商品數
private final int MAX_SIZE; //當前商品數 private int count; public Store(int size) { MAX_SIZE = size; count = 0; } //增加商品 public synchronized void add() { if(count>=MAX_SIZE) { System.out.println(Thread.currentThread().getName()+" Store is full, please to get. count:"+count);
try{ this.wait(); }catch(InterruptedException e) { e.printStackTrace(); } }else{ System.out.println(Thread.currentThread().getName()+" custom :current count: "+count); count++; this.notifyAll(); } } //移除商品 public synchronized void remove() { if(count<=0) { System.out.println(Thread.currentThread().getName()+" Store is empty,please input. count:"+count); try{ this.wait(); }catch(InterruptedException e){ e.printStackTrace(); } }else{ count--; System.out.println(Thread.currentThread().getName()+" product: current count: "+count); this.notifyAll(); } } } //消費者 class Custom extends Thread { Store store; public Custom(Store store) { this.store = store; } @Override public void run() { while(true){ store.remove(); try { Thread.sleep(1500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } //生產者 class Product extends Thread { Store store; public Product(Store store) { this.store = store; } @Override public void run() { while(true){ store.add(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }

多線程簡單實例(2)生產者和消費者