⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shop.java

📁 java生产者消费者程序实现   线程
💻 JAVA
字号:

 public class Shop 		              //定义一个商店类
   {
    private int breadNumber;	        	//面包的数量,作为临界资源
	private int breadMaxSize;              //商店里能存放面包的最大容量的个数
	public int numberInWaitingPool;       //shop对象的等待池中等待者的数量
	public Shop(int breadMaxSize)    //定义构造函数
	{
	  this.breadMaxSize=breadMaxSize;
	}
	public synchronized void makeBread()   //"生产面包"操作,对临界资源的访问
	{
	   while (breadNumber==breadMaxSize)		//商店中的面包已满
	   {
		try {
			try{
	 			Thread.sleep(2000);
	 		}
	 		catch(InterruptedException e)
	 		{
	 		} 
			System.out.print(  Thread.currentThread().getName()+"又想做新的面包...但是商店不能再放更多的面包了...所以");
			System.out.println( Thread.currentThread().getName()+"被送入shop对象的等待池中.\n");
			this.numberInWaitingPool++;
			try{
	 			Thread.sleep(2000);
	 		}
	 		catch(InterruptedException e)
	 		{
	 		} 
			this.wait();     //当前线程进入等待状态(即挂起状态)
			} 
	 	catch (InterruptedException e) {}
   		 }
		this.breadNumber++;				//商店中面还能放面包,生产面包,则面包数量加1
		try{
	 			Thread.sleep(2000);
	 		}
	 		catch(InterruptedException e)
	 		{
	 		} 
		System.out.print("  商店还有"+this.breadNumber+"个面包.");
		
		if (this.numberInWaitingPool>0)	//等待池中有处于等待状态的线程
		{
			this.notifyAll();			//随机从shop对象的等待池中唤醒一个线程
			
			System.out.print("(商店里面又有面包了,所以从shop对象的等待队列中走出一个线程),");
			this.numberInWaitingPool--;	//等待池中线程数量减1
     	}
	}
		public synchronized void eatBread()   //"吃面包"操作,对临界资源的访问
		{
		while(breadNumber==0){			//商店中已经没有面包了
		try {	
		  try{
	 			Thread.sleep(2000);
	 	   	}
	 		catch(InterruptedException e)
	 		{
	 		} 
	    	System.out.print( Thread.currentThread().getName()+"又来吃了...但是商店已经没有面包了...所以");
		    System.out.println(Thread.currentThread().getName()+"被送入shop对象的等待池中.");
		    this.numberInWaitingPool++;
		    this.wait();    //当前线程进入等待状态,即挂起状态
		} 
		catch (InterruptedException e) {}
		}
		this.breadNumber--;				//商店中若有面包,吃了一块面包后,则其数量减1
		try{
	 			Thread.sleep(2000);
	 		}
	 		catch(InterruptedException e)
	 		{
	 		} 
		System.out.print("  商店还有"+this.breadNumber+"个面包.");
		
		if (this.numberInWaitingPool>0)		//等待池中有处于等待状态的线程
		{
			
			this.notifyAll();				//随机从shop对象的等待池中唤醒一个线程
			System.out.print("(商店中空间有富余了.从shop对象的等待池中走出一个线程),");
			this.numberInWaitingPool--;		//等待池中现成数量减1
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -