打印机-顾客进程同步

    系统中有一个打印进程Printer和若干顾客进程Customer_ii>20)。缓冲池有5个缓冲区。如果

Customer_i进程要打印,则Printer进程阻塞。当Customer_i进程需要打印时,唤醒Printer进程;如果

没有缓冲区,Customer_i则必须放弃打印。请设计同步机制实现以上要求。


package customer;


public class ProducerConsumer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
        SyncStack ss=new SyncStack();
        Printer p=new Printer(ss);
        Consumer c=new Consumer(ss);
        new Thread(p).start(); 
        new Thread(c).start();
	}

}
class file{
	int id;
    file(int id){
		this.id=id;
	}
	public String toString(){
		return "第:"+id;
	}
}
这个方法是同步的方法,每次只有5个线程可以进来
class SyncStack { 
	 int index = 0; 
	 file[] arrWT = new file[5]; 
	 public synchronized void push(file wt) { 
	  while(index == arrWT.length) { 
	   try { 
		   System.out.println("没有空闲的打印机了,请等待!");
		   System.out.println(wt+"为放弃打印的文件");
	       this.wait(); 
	   } catch (InterruptedException e) { 
	    e.printStackTrace(); 
	   } 
	  } 
	  this.notifyAll();   
	  arrWT[index] = wt; 
	  index ++; 
	  System.out.println(wt+"个顾客"+"打印了, "+wt+"份文件");
	 } 

	 public synchronized file pop() { 
	  while(index == 0) { 
	   try {
		System.out.println("店里没人了!");
	    this.wait(); 
	   } catch (InterruptedException e) { 
	    e.printStackTrace(); 
	   } 
	  } 
	  this.notifyAll(); 
	  index--; 
	  System.out.println(arrWT[index]+"份文件打印完毕,店里剩余"+index+"顾客");
	  return arrWT[index]; 
	 } 
	} 
	 
	class Printer implements Runnable { 
	 SyncStack ss = null; 
	 Printer(SyncStack ss) { 
	  this.ss = ss; 
	 } 

//打印进程	  
public void run() { 
  for(int i=0; i<25; i++) { 
	 file wt = new file(i);
	 ss.push(wt);
	 try{
		 Thread.sleep((int)(Math.random()*200));
	  }catch(InterruptedException e){
		 e.printStackTrace();
	  }
   }
  }
}
	
class Consumer implements Runnable { 
	SyncStack ss = null; 
	Consumer(SyncStack ss) { 
		this.ss = ss; 
	 } 

//顾客进程		 
 public void run() { 
    for(int i=0; i<25; i++) {
    	ss.pop(); 
    	//System.out.println("打印了: " + wt);
    	try { 
		  Thread.sleep((int)(Math.random() * 1000)); 
		} catch (InterruptedException e) { 
		   e.printStackTrace(); 
		 }    
       } 
  } 

}
	 

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值