生产者和消费者成功解答synchroniz…

来源:互联网 发布:网络设计岗位要求 编辑:程序博客网 时间:2024/06/01 13:54

class Storage {//仓库类,用于生产产品和消费产品
 int n;
 boolean valueSet = false;

 synchronized int get() {//消费产品
   while(!valueSet)
     try{
      wait();//消费者消耗了产品后需要wait,来等待生产者生产产品

     }catch(InterruptedException e) {
     
      System.out.println("InterruptedExceptioncaught");
    }
    try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    System.out.println("Got: " + n);
    valueSet = false;
    notify();//当产品消费了之后,需要唤醒被wait的put()来生产产品
     returnn;
 }

 synchronized void put(int n) {//生产产品
   while(valueSet)
     try{
      wait();//当valueSet为true时,停止生产产品
     }catch(InterruptedException e) {
      System.out.println("InterruptedExceptioncaught");
    }

     this.n= n;
    valueSet = true;
     try{
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    System.out.println("Put: " + n);
    notify();//put()生产了产品后需要唤醒消费者去get()消耗产品
 }
}

class Producer implements Runnable {
Storage q;

 Producer(Storage q) {
   this.q = q;
   new Thread(this,"Producer").start();
 }

 public void run() {
   int i = 0;

   while(true) {
    q.put(i++);
   }
 }
}

class Consumer implements Runnable {
Storage q;

 Consumer(Storage q) {
   this.q = q;
   new Thread(this,"Consumer").start();
 }

 public void run() {
   while(true) {
    q.get();
   }
 }
}

class consumer_producer {
 public static void main(String args[]){
 Storage q = new Storage();
   new Producer(q);
   new Consumer(q);

   System.out.println("PressControl-C to stop.");
 }
}


生产者和消费者成功解答synchronized <wbr>的疑惑

0 0