• java167-生产者消费者问题


    class Ck {
         private char[] r1 = new char[8];
         private int wp = 0;
     
         public synchronized void shengchan(char aa) {
             while (wp == r1.length) //满了
                 try {
                     this.wait();
                 } catch (Exception e) {
                 }
                 this.notify();//叫醒另一个线程,当前线程处于就绪状态
                 r1[wp] = aa;
                 ++wp;
                 System.out.println( "生产者正在生产第" + wp + "个产品,该产品为" + aa );
     
         }
     
         public synchronized void xiaofei() {
             char aa;
             while (wp == 0)
                 try {
                     this.wait();
                 } catch (Exception e) {
                 }
                 this.notify();
                 aa = r1[wp - 1];
                 System.out.println( "生产者正在消费第" + wp + "个产品,该产品为" + aa );
                 --wp;
     
         }//代码生产消费问题实现
     
     }
    定义生产

    //生产
    public class Sc implements Runnable {
        private Ck xc = null;
        public Sc(Ck xc) {
            this.xc = xc;
        }
        public void run() {
            char aa;
            for (int i = 0; i < 26; i++) {
                aa = (char) ('A' + i);
                xc.shengchan( aa );
            }
        }
     
    }
    定义消费

    //消费
    public class Xf implements Runnable {
        private Ck xc = null;
        public Xf(Ck xc) {
            this.xc = xc;
        }
        public void run() {
     
            char aa;
            for (int i = 0; i < 26; i++) {
                aa = (char) ('A' + i);
                xc.xiaofei();
            }
        }
     
    }
    测试类

    //代码生产消费问题实现
     
        public class test119{
        public static void main(String[] args){
            Ck ck=new Ck();
            Sc sc=new Sc( ck );
            Xf xf=new Xf(ck);
            Thread xc1=new Thread( sc );
            xc1.start();
            Thread xc2=new Thread( xf );
            xc2.start();
     
        }
        }
     
     
     
    运行结果

     

  • 相关阅读:
    vue+elementUI
    【Python基础】面向对象封装 案例(一)
    spring框架源码九、spring ioc xml与注解组合模式
    Android-Firebase合规问题解决方案-详细攻略,debug模式破解难题
    【超详细】Promise原理及执行顺序详解
    [软件安装] tmux安装及相关事项
    【SpringBoot笔记28】SpringBoot集成ES数据库之操作doc文档(创建、更新、删除、查询)
    新加坡服务器托管:开启全球化发展之门
    Spring核心与设计思想
    搜索技术——模拟退火算法
  • 原文地址:https://blog.csdn.net/qq_41632427/article/details/125478190