zoukankan      html  css  js  c++  java
  • 生产者消费者

    注:处于wait状态下的线程没有被唤醒,不能去抢锁

    1.容器

    public class Stack {
        char[] a=new char[5];
        int i;
        //压入
        void pull(char s){
            if (i==5) {
                return;
            }
            a[i]=s;
            i++;
        }
        //取出
        char push(){
            if (i==0) {
                return ' ';
            }
            i--;
            return a[i];
        }
        int size(){
            return i;
        }
    }

    2.生产者

    public class Producer extends Thread{
        private Stack stack;
        public Producer(Stack stack) {
            this.stack=stack;
        }
        @Override
        public void run() {
            while (true) {
                synchronized (stack) {
                    while (stack.size()==5) {
                        System.out.println("盘子满了,需等待");
                        try {
                            stack.wait();
                        } catch (InterruptedException e) {
                            System.out.println("盘子满了,需等待");
                        }
                    }
                    char a = (char) ('a'+new Random().nextInt(26));
                    stack.pull(a);
                    System.out.println("压入数据 : "+a);
                    //压入数据后发出通知,盘子里面有数据了
                    stack.notifyAll();
                }
            }
        }
    }

    3.消费者

    public class Consumer extends Thread {
        private Stack stack;
        public Consumer(Stack stack) {
            this.stack=stack;
        }
        @Override
        public void run() {
            while (true) {
                synchronized (stack) {
                    while (stack.size()==0){
                        System.out.println("盘子里面没有数据,需等待");
                        try {
                            stack.wait();
                        } catch (InterruptedException e) {
                            System.out.println("盘子里面没有数据,需等待");
                        }
                    }
                    char a = stack.push();
                    System.out.println("取出数据 : "+a);
                    //取出数据后发出通知,盘子里面可以放东西了
                    stack.notifyAll();
                }
            }
        }
    }

    4.测试

    public class Test {
        public static void main(String[] args) {
            Stack stack = new Stack();
            Producer producer = new Producer(stack);
            Consumer consumer = new Consumer(stack);
            producer.start();
            consumer.start();
    
        }
    } 
  • 相关阅读:
    如何在Eclipse中显示行号
    最值得听的100首英文歌
    ffmpeg示例一:源码
    编码解码中常用术语二
    ffmpeg.c(ffmpeg.exe)调试笔记一
    Debug ffmpeg.c & ffmpeg_g.exe in Ubuntu with Eclipse
    ubuntu下编译ffmpeg with libx264
    利用ffmpeg切割与合并视频(一)调用ffmpeg程序直接切割
    VMWare安装Ubuntu 12.10无法开启虚拟机的Unity Mode模式
    Atitit.基于dsl的methodinvoker
  • 原文地址:https://www.cnblogs.com/gxlaqj/p/11697770.html
Copyright © 2011-2022 走看看