zoukankan      html  css  js  c++  java
  • 生产者与消费者模式之管程法

    package Tread;
    
    public class TestProduce {
    	public static void main(String[] args) {
    		Systack sy = new Systack();
    		Shengchan sc = new Shengchan(sy);
    		XiaoFei xf = new XiaoFei(sy);
    		new Thread(xf).start();
    		new Thread(sc).start();
    	}
    }
    
    class ManTou {
    	int id;
    
    	ManTou(int x) {
    		id = x;
    	}
    
    	public ManTou() {
    		// TODO Auto-generated constructor stub
    	}
    }
    
    class Systack {
    	int index = 0;
    	ManTou[] mt = new ManTou[10];
    
    	public synchronized void push(ManTou m) {
    		while (index == mt.length) {
    			try {
    				this.wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		this.notify();
    		mt[index] = m;
    		index++;
    	}
    
    	public synchronized ManTou pop() {
    		while (index == 0) {
    			try {
    				this.wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		this.notify();
    		index--;
    		return mt[index];
    	}
    }
    
    class XiaoFei implements Runnable {
    	Systack sc = null;
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 20; i++) {
    			ManTou m = sc.pop();
    			System.out.println("吃馒头");
    		}
    
    	}
    
    	public XiaoFei(Systack sc) {
    		super();
    		this.sc = sc;
    	}
    
    }
    
    class Shengchan implements Runnable {
    	Systack sc = null;
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 20; i++) {
    			System.out.println("造馒头");
    			ManTou mt = new ManTou(i);
    			sc.push(mt);
    		}
    	}
    
    	public Shengchan(Systack sc) {
    		super();
    		this.sc = sc;
    	}
    }
    

      

  • 相关阅读:
    python基础语法
    java关键字之final
    汉字占几个字节?
    Java学习记录(补充二:面对对象基础复习,习题)
    Java学习记录(补充二)
    Java学习记录(补充一(以习题为主:判断,循环语句))
    Java学习记录
    JS学习记录(jQuery补充一)
    JS学习记录(jQuery)
    JS学习记录(数组补充一)
  • 原文地址:https://www.cnblogs.com/yjxs/p/9849205.html
Copyright © 2011-2022 走看看