`

java基础之线程同步实例之Producer与Consumer

 
阅读更多

转自: http://blog.csdn.net/liuyu832/article/details/6287159

 

 

class Producer implements Runnable{
 
 Message ms =new Message();
 int i = 0;
 
 Producer(Message ms){
  this.ms = ms;
 }
 
 public void run(){
  while(true){
   if(i > 10){
    break;
   }else{ 
    System.out.println("Producer set :"+i);
    ms.setMessage(i);
   
    i++;
   }
  }
 }
}

class Consumer implements Runnable{
 
 Message ms =new Message();
 
 Consumer(Message ms){
  this.ms = ms;
 }
 
 public void run(){
  while(true){
   if(ms.i >= 10){
    System.out.println(" is over!..");
    break;
   }
   try{
    Thread.sleep(100);
   }catch(Exception e){
    e.getStackTrace();
   } 
   int i = this.ms.getMessage();
   System.out.println("Consumer get :"+i);
  }
 }
}

class Message{
 public int i;
 synchronized int getMessage(){
  notify();
  return this.i; 
 }
 
 synchronized void setMessage(int i){
  this.i = i;
  try{
   wait();
  }
  catch(Exception e){
   e.printStackTrace();
  }
 }
}

/* (1)调用wait()和notify()方法需要注意 方法调用者都是同一个对象;
 (2)一定要用 synchronized(){}实现同步;*/
public class Main {
 public static void main(String[] args){
  Message ms = new Message();
  Producer p = new Producer(ms);
  Consumer c = new Consumer(ms);
  Thread t1 = new Thread(p);
  Thread t2 = new Thread(c);
  t1.start();
  t2.start();
 }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics