信号量在多线程通讯运用

同步的三个方法:

   必须在同步块 或者同步方法中使用

  1. notify()  停止访问当前线程,转去执行挂起的线程
  2. notifyALL()
  3. wait() 挂起 释放对线程资源的访问
class CommonTalkVar{
      private char product;
      /**同步信号量
       *  true: 持有产品状态
       *  false: 已经消费产品状态
       * */
      private  boolean isProduced=false;

    /**
     * @description production method
     */
    public synchronized void putCommonData(char product){
            if(isProduced){
                try {
                    System.out.println(Thread.currentThread().getName()+"消费者还没有消费产品");
                    wait();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            this.product=product;
            this.isProduced=true;
            System.out.println(Thread.currentThread().getName()+"生产者生产:"+this.product);
            notify();
    }
    /**
     * @description consumer method
     */
    public synchronized char getCommonData(){
        if(!isProduced){
            try {
                System.out.println(Thread.currentThread().getName()+"生产者还没有生产产品");
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        this.isProduced=false;
        System.out.println(Thread.currentThread().getName()+"消费者消费:"+this.product);
        notify();
        return this.product;
    }
}

class Consumer extends Thread{
    private CommonTalkVar commonTalkVar;

    public Consumer(CommonTalkVar commonTalkVar){
        this.commonTalkVar=commonTalkVar;
    }

    @Override
    public  void run() {
        char tempc;
        do{
            try {
                Thread.sleep((int)(Math.random()*3000));
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            tempc=commonTalkVar.getCommonData();
        }while (tempc!='D');
    }
}

class Product extends Thread{
    private CommonTalkVar commonTalkVar;
    public Product(CommonTalkVar commonTalkVar){
        this.commonTalkVar=commonTalkVar;
    }

    @Override
    public  void run() {
        for (char i = 'A'; i <= 'D'; i++){
            try {
                Thread.sleep((int)(Math.random()*3000));
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            commonTalkVar.putCommonData(i);
        }
    }
}

public class ConsumerAndProduct {
    public static void main(String[] args) {
        CommonTalkVar talkVar = new CommonTalkVar();

        new Consumer(talkVar).start();
        new Product(talkVar).start();
    }
}

猜你喜欢

转载自www.cnblogs.com/dgwblog/p/11681511.html