`
befairy
  • 浏览: 36387 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

java--线程生产消费者问题

阅读更多

产品苹果类
package producter_consumer;

public class Apple {
     private int num=0;
     
     public void setNum(int num){
    	 this.num=num;
     }
     public int getNum(){  
    	 return num;
     }
     //生产苹果产品
     public synchronized void produce(){
    	 num++;
    	 System.out.println("生产了一个苹果,现在数量为:"+num);
    	 this.notifyAll();
     }
     //消费苹果产品
     public synchronized void consume(){
    	 num--;
    	 System.out.println("消费了一个苹果,现在数量为:"+num);
    	 this.notifyAll();
     }
     //此方法根据当前的苹果数量来判断是否应该生产苹果产品
     public synchronized void waitForProduce() {
    	 while(num<1){
    		 System.out.println("等待生产中...");
    		 try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    	 }
     }
     //此方法根据当前的苹果数量来判断是否能够消费苹果产品
     public synchronized void waitForConsume(){
    	 while(num>10){
    		 System.out.println("等待消费中...");
    		 try {
				this.wait();
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			}
    	 }
     }
}




<--------------------------可爱的分割线------------------------------->
生产类
package producter_consumer;

import java.lang.Thread;

public class Produce implements Runnable{

	Apple apple=null;
	
	public Produce(Apple ap){
		this.apple=ap;
	}
	
	public void run() {
		int m=20;
		try {
	        while(m>0){
		
				Thread.sleep(1000);
				apple.waitForConsume();
				System.out.println("正在准备生产...");
				apple.produce();
				System.out.println("现在苹果数量为:"+apple.getNum());
			
			    m--;
	        }
        } catch (InterruptedException e) {
    		
			e.printStackTrace();
		}
		
		
	}

}



<--------------------------可爱的分割线------------------------------->
消费类

package producter_consumer;

import java.lang.Thread;

public class Consume implements Runnable {

	Apple apple=null;
	
	public Consume(Apple ap){
		this.apple=ap;
	}
	
	public void run() {
         int m=20;
         try {
              while(m>0){
        	
					Thread.sleep(5000);
					apple.waitForProduce();
					System.out.println("正在准备消费...");
					apple.consume();
					System.out.println("现在苹果数量为:"+apple.getNum());
				    m--;
              }
         } catch (InterruptedException e) {
				
				e.printStackTrace();
		 }

	}

}



<--------------------------可爱的分割线------------------------------->
生产消费测试类


package producter_consumer;

import java.lang.Thread;

public class PCTest {

	
	public static void main(String[] args) throws InterruptedException {
		Apple apple=new Apple();
		Produce p=new Produce(apple);
		Consume c=new Consume(apple);
		
		new Thread(p).start();
		new Thread(c).start();
		
		Thread.sleep(10000);
		//安全退出
        //System.exit(0);
	}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics