经典进程的同步问题-生产者与消费者

时间:2021-11-09 20:20:03

 在说到进程的同步的问题上,毫无疑问,生产者与消费者这个经典问题是不可避免的。


                                             经典进程的同步问题-生产者与消费者

生产者生产的前提是:生产者生产出来的产品容器还能够装下,否则等待消费者消费;

消费者消费的前提是:容器中有产品能够让消费者消费,否则等待生产者生产;

public class Test {
	public static void main(String[] args){
	Store s=new Store();    
	Productor p1=new Productor(s);
	Customers c1=new Customers (s);

        Thread s1=new Thread(p1,"生产者1");
	Thread s2=new Thread(p1,"生产者2");
	Thread s3=new Thread(p1,"生产者3");
	Thread s4=new Thread(p1,"生产者4");
	
	Thread s5=new Thread(c1,"消费者1");
	Thread s6=new Thread(c1,"消费者2");
	Thread s7=new Thread(c1,"消费者3");

	s1.start();
	s2.start();
	s3.start();
	s4.start();
	s5.start();
	s6.start();
	s7.start();
	
}
}
生产者类:

public class Productor implements Runnable {
	     Store s;
	     public Productor(Store s){
	    	 this.s=s;
	     }
	@Override
	public void run() {
		  while(true)
          s.SetGoods();
		
	}
}
消费者类:

public class Customers implements Runnable{
	   Store s;
     public Customers(Store s){
    	 this.s=s;
     }
	@Override
	public void run() {
		while(true)
		s.GetGoods();
	}

}
存储的仓库类:

public class Store {
	    //容器中可以存放的最大的产品的数目
	    int max=50;
	    //容器中某一时刻的产品数
	    int nowGood=0;
       public synchronized void  SetGoods(){
    	      if(nowGood<max){
    		    try {
			 Thread.sleep(50);
			} catch (InterruptedException e) {
			  e.printStackTrace();
				}
    		   nowGood= nowGood+1;
    		   System.out.println(Thread.currentThread().getName()+"生产了第"+nowGood+"个产品");
    	   }
    	  
       }
       
       public  synchronized void GetGoods(){ 
    	             if(nowGood>0){ 
        	              try {
  					Thread.sleep(100);
  				} catch (InterruptedException e) {
  				e.printStackTrace();
  				}
      		   System.out.println(Thread.currentThread().getName()+"消费了第"+nowGood+"个产品"); 
      		   nowGood= nowGood-1;
      	   }
      }
}
经典进程的同步问题-生产者与消费者

这里应该注意就是加锁的时候一定要在while循环的里面。