zoukankan      html  css  js  c++  java
  • 编写一个多线程程序,模拟2个生产者生产产品,3个消费者消费产品。2个生产者不停的生产商品3个消费者不停的消费产品。

    粗略代码:

    class Resource
    {
    	private String name;
    	private int count = 0;
    	private boolean flag = true;
    	Resource(String name)
    	{
    		this.name = name;
    	}
    
    	public synchronized void product()
    	{
    		if(flag)
    		{
    			this.name = "---"+this.count;
    			System.out.println(Thread.currentThread().getName() + "生产者---" + this.name);
    		}
    
    		flag  = false;
    		this.count++;
    	}
    	
    	public synchronized void consume()
    	{
    		if(!flag)
    		{
    			System.out.println(Thread.currentThread().getName() + "消费者---------" + this.name);
    		}
    
    		flag = true;
    	}
    }
    
    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();
    	}
    }
    


  • 相关阅读:
    2-3-4 tree留坑
    CCPC final Cockroaches
    对拍模板
    使用cronolog按日期分割日志
    linux git 命了
    变量加减乘除运算
    根据pom标签修改
    根据符号获取字符
    shell循环字符串数组
    git ssh key配置
  • 原文地址:https://www.cnblogs.com/dengshiwei/p/4258539.html
Copyright © 2011-2022 走看看