多线程,生产者消费者模型(生产馒头,消费馒头)
先建立一个容器
/** * 容器 * 共享资源 * @author Administrator * */ public class SynStack { int index = 0; //容器 SteamBread[] stb = new SteamBread[6]; /** * 往容器中放产品 */ public synchronized void push(SteamBread st){ while(index == stb.length){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } notify();//唤醒正在等待的线程 stb[index] = st; this.index++; } /** * 从容器中取产品 */ public synchronized SteamBread pop(){ while(index == 0){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } notify(); this.index--; return stb[index]; } }
产馒头
package com.newer.cn; public class Producer implements Runnable{ SynStack ss = null; public Producer(SynStack ss) { // TODO Auto-generated constructor stub this.ss = ss; } @Override public void run() { //开始生产馒头 for(int i = 1;i <= 20;i++){ SteamBread stb = new SteamBread(i); System.out.print("生产了::::::"); ss.push(stb); System.out.println("生产了"+stb); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
消费馒头
package com.newer.cn; public class Consume implements Runnable{ SynStack ss = null; public Consume(SynStack ss) { this.ss = ss; } @Override public void run() { //开始消费馒头 for(int i = 1;i <= 20;i++){ System.out.print("消费了::::::"); SteamBread stb = ss.pop(); System.out.println("消费了"+stb); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
测试
package com.newer.cn; public class Test2 { public static void main(String[] args) { SynStack ss = new SynStack(); //生产者线程 Producer p = new Producer(ss); Thread tp = new Thread(p); //消费者线程 Consume c = new Consume(ss); Thread tc = new Thread(c); tp.start(); tc.start(); } }