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;
    	}
    }
    

      

  • 相关阅读:
    Hadoop作业提交多种方案具体流程详解
    教你一步搭建Flume分布式日志系统
    Hadoop详细配置
    linux 运行springboot sqoop项目
    SQL+ 正则表达式
    SQL+ 正则表达式
    DB2中实现正则表达式
    DB2中实现正则表达式
    spring4整合cxf3
    spring4整合cxf3
  • 原文地址:https://www.cnblogs.com/yjxs/p/9849205.html
Copyright © 2011-2022 走看看