线程通信解决生产者消费者问题

线程通信解决生产者消费者问题

求解的过程写在注释里了

package com.gen.test;


/**
 * @ClassName : CommunicationDemo
 * @Author : ShiGen
 * @Date: 2021/3/27 16:38
 * @Description : ${description}
 */
public class CommunicationDemo {
    public static void main(String[] args){
        sharedResores sharedResores = new sharedResores ( );
        new Consuer ( sharedResores ).start ( );
        new Producer ( sharedResores ).start ( );
    }
}

class sharedResores {
    private char c;
    //    标记还没有生产
    private boolean isProduced = false;

    synchronized void putShareChar(char c){
  /*      没生产是因为消费者还没有消费——等待
        生产了唤醒消费者消费
        */
//      没有在生产是因为在等待消费
        if(isProduced){
            try{
                System.out.println ( "没有消费,生产者停止生产" );
                wait ( );
            } catch(InterruptedException e){
                e.printStackTrace ( );
            }
        }
        this.c = c;
//        已经生产了,通知消费者
        isProduced = true;
        notify ( );
        System.out.println ( "生产了 " + c + " 消费者来消费" );
    }

//    同步的方法获得当前的资源
    synchronized char getShareChar( ){
        if(!isProduced){
            try{
                System.out.println ( "生产者正在生产,等待一伙儿" );
                wait ( );
            } catch(InterruptedException e){
                e.printStackTrace ( );
            }
        }
        isProduced = false;
        notify ( );
        System.out.println ( "消费了 " + c + " 通知生产者生产" );
        return this.c;
    }
}

class Producer extends Thread {
    private sharedResores sharedResores;

    Producer(sharedResores sharedResores){
        this.sharedResores = sharedResores;
    }

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

class Consuer extends Thread {
    private sharedResores sharedResores;

    Consuer(sharedResores sharedResores){
        this.sharedResores = sharedResores;
    }

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




运行的结果

生产了 A 消费者来消费
消费了 A 通知生产者生产
生产了 B 消费者来消费
消费了 B 通知生产者生产
生产了 C 消费者来消费
消费了 C 通知生产者生产
生产了 D 消费者来消费
消费了 D 通知生产者生产

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值