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

      

    的物品被生产出来

  • 相关阅读:
    设计模式总结
    JWT、OAUTH2与SSO资料补充
    dajie项目的坑
    fw-cloud-framework项目配置、启动问题
    Shiro源码分析
    (转)JPA & Restful
    Spring Boot以War包启动
    (转)Spring & SpringMVC学习
    MySQL的数据类型(二)
    MySQL的数据类型(一)
  • 原文地址:https://www.cnblogs.com/hlongch/p/5727192.html
Copyright © 2011-2022 走看看