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


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();
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值