[JAVA 多線程] 生產者消費者執行個體

來源:互聯網
上載者:User

標籤:

正好有人問,就直接將代碼記錄下來。

 

背景:有一個倉庫儲存貨物,存在著生產者和消費者,設計一個可以並發的實現。

設計思路:設計一個倉庫類,類中儲存最大的容量限制和當前的count,類中包含生產和消費的方法,並且都是synchronized。

具體代碼:

package com.test.tiny;public class Store {    private final int MAX_SIZE; //最大    private int count; // 當前        public Store(int n) {        MAX_SIZE = n;        count = 0;    }        public synchronized void add() {        while(count >= MAX_SIZE) {            System.out.println("已經滿了");            try {                this.wait();            } catch (InterruptedException e) {                e.printStackTrace();            }        }        count++;        System.out.println(Thread.currentThread().toString() + " put :" + count);        this.notifyAll();    }        public synchronized void remove() {        while(count <= 0) {            System.out.println("已經空了");            try {                this.wait();            }catch(Exception e) {                e.printStackTrace();            }        }                System.out.println(Thread.currentThread().toString() + " get :" + count);        count--;        this.notifyAll();    }        public static void main(String[] args) {        // TODO Auto-generated method stub        Store s = new Store(5);        Thread pro = new Producer(s);        Thread con = new Consumer(s);        Thread pro2 = new Producer(s);        Thread con2 = new Consumer(s);                pro.setName("生產者1");        con.setName("消費者1");        pro2.setName("生產者2");        con2.setName("消費者2");                pro.start();        con.start();        pro2.start();        con2.start();    }}class Producer extends Thread {    private Store s;    public Producer(Store s) {        this.s = s;    }    public void run() {        while(true) {            s.add();            try {                Thread.sleep(1000);  // 為了直觀,休息1秒            }catch(Exception e) {                e.printStackTrace();            }        }    }}class Consumer extends Thread {    private Store s;        public Consumer(Store s) {        this.s = s;    }        public void run() {        while(true) {            s.remove();            try {                Thread.sleep(1500); // 為了直觀 多休息0.5秒            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

 

[JAVA 多線程] 生產者消費者執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.