zoukankan      html  css  js  c++  java
  • 生产,消费者改进

    /*
    等待的目的是让cpu给其他线程。
    */
    class Resource
    {
    	private String name;
    	private int count = 0;
    	private boolean flag = false;
    	Resource(String name)
    	{
    		this.name = name;
    	}
    
    	public synchronized void product()
    	{
    		while(flag)						//此处如果是if的效果
    		{
    			try
    			{
    				wait();
    			}
    			catch (InterruptedException ex)
    			{
    				
    			}
    		}
    
    		this.name = "---"+this.count;
    		System.out.println(Thread.currentThread().getName() + "生产者---" + this.name);
    		flag  = true;
    		this.count++;
    		this.notify();
    	}
    	
    	public synchronized void consume()
    	{
    		while(!flag)					//此处如果是if的效果,如果某个线程被wait,接着又一个,然后两个都醒了,就会造成对一个产品两次消费
    		{
    			try
    			{
    				wait();
    			}
    			catch (InterruptedException ex)
    			{
    			}
    		}
    
    		System.out.println(Thread.currentThread().getName() + "消费者---------" + this.name);
    		flag = false;
    		this.notify();
    	}
    }
    
    class Product implements Runnable
    {
    	private Resource sr;
    	Product(Resource sr)
    	{
    		this.sr = sr;
    	}
    
    	public void run()
    	{
    		while(true)
    		{
    			if(sr != null)
    			{
    				sr.product();
    			}
    		}
    	}
    }
    
    class Consume implements Runnable
    {
    	private Resource sr;
    	Consume(Resource sr)
    	{
    		this.sr = sr;
    	}
    
    	public void run()
    	{
    		while(true)
    		{
    			if(sr != null)
    			{
    				sr.consume();
    			}
    		}
    	}
    }
    class DemoRunnable
    {
    	public static void main(String[] args) 
    	{
    		Resource sr = new Resource("产品");
    		Product p = new Product(sr);
    		Consume c =new Consume(sr);
    		Thread t1 = new Thread(p);
    		Thread t2 = new Thread(p);
    		Thread c1 = new Thread(c);
    		Thread c2 = new Thread(c);
    		Thread c3 = new Thread(c);
    		t1.start();
    		t2.start();
    		c1.start();
    		c2.start();
    		c3.start();
    	}
    }
    

  • 相关阅读:
    Linux:闪光的宝石,智慧 (在)
    采用jqueryUI创建日期选择器
    C++学习笔记9-运算符重载
    spring mvc综合easyui点击上面菜单栏中的菜单项问题
    TCP拥塞控制 (1)
    牛顿迭代法
    【6】和作为连续序列s
    动态规划-简介
    约瑟夫环问题
    j简单的递归
  • 原文地址:https://www.cnblogs.com/dengshiwei/p/4258538.html
Copyright © 2011-2022 走看看