zoukankan      html  css  js  c++  java
  • 生产者消费者线程同步

    生产者与消费者模式简单介绍:

      生产者线程生产物品,然后将物品放置在一个空缓冲区中供消费者线程消费。消费者线程从缓冲区中获得物品,然后释放缓冲区。当生产者线程生产物品时,如果没有空缓冲区可用,那么生产者线程必须等待消费者线程释放出一个空缓冲区。当消费者线程消费物品时,如果没有满的缓冲区,那么消费者线程将被阻塞,直到新

    public class ProduceConsumer {
    	
    	public static void main(String[] args) {
    		SyncStack ss = new SyncStack();
    		Producer pro = new Producer(ss);
    		Consumer con = new Consumer(ss);
    		new Thread(pro).start();
    		new Thread(con).start();
    	}
    
    }
    class Product{
    	int id;
    	public Product(int id){
    		this.id = id;
    	}
    	public String toString(){
    		return "Product:"+id;
    	}
    }
    
    class SyncStack{
    	int index = 0;
    	Product[] arrPro = new Product[6];
    	public synchronized void push(Product p){
    		while(index == arrPro.length){
    			try {
    				this.wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		
    		this.notify();
    		arrPro[index] = p;
    		index++;
    	}
    	public synchronized Product pop(){
    		while(index == 0){
    			try {
    				this.wait();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    		this.notify();
    		index--;
    		return arrPro[index];
    	}
    }
    
    class Producer implements Runnable{
    	SyncStack ss = null;
    	public Producer(SyncStack ss){
    		this.ss = ss;
    	}
    	public void run(){
    		for(int i=0; i<20; i++){
    			Product p = new Product(i);
    			ss.push(p);
    			System.out.println("生产了:"+p);
    			try {
    				Thread.sleep(100);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    }
    
    
    class Consumer implements Runnable{
    	SyncStack ss = null;
    	public Consumer(SyncStack ss){
    		this.ss = ss;
    	}
    	public void run(){
    		for(int i=0; i<20; i++){
    			Product p = ss.pop();
    			System.out.println("消费了:"+p);
    			try {
    				Thread.sleep(1000);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    }
    

      

    的物品被生产出来

  • 相关阅读:
    Javascript里的那些距离们
    Javascript Date类常用方法详解
    JQuery学习笔记
    淘宝、百度、网易、搜狐前端开发面试题集锦 及 答案 【陈旧,不宜再看】
    javascript 注意事项
    jQuery对象和javascript对象互换
    那些 Android 程序员必会的视图优化策略
    那些 Android 程序员必会的视图优化策略
    mysql explain用法
    Laravel如何与App交互(针对get与post)
  • 原文地址:https://www.cnblogs.com/hlongch/p/5727192.html
Copyright © 2011-2022 走看看