zoukankan      html  css  js  c++  java
  • 自我实现消费者生产者实例

    //操作对象
    public
    class BookCase { private String book; private boolean available = false; public synchronized String get() { while (!available) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("get<==============:"+book); available = false; notifyAll(); return book; } public synchronized void put(String newBook){ while(available){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("put==============>:"+newBook); available = true; notifyAll(); book = newBook; } }

      

    //生产者
    public class Producer extends Thread{ private BookCase bookCase; public Producer(BookCase bookCase){ this.bookCase = bookCase; } public void run(){ for(int i=0;i<10;i++){ String book = "Book"+i; bookCase.put(book); // try { // sleep((int)Math.random()*1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } } } }

      

    //消费者
    public class Consumer extends Thread{
        private BookCase bookCase;
    
        public Consumer(BookCase bookCase){
            this.bookCase = bookCase;
        }
    
        public void run(){
            for(int i=0;i<10;i++){
                String book = bookCase.get();
    //          System.out.println("Consumer "+i+" get: "+book);
            }
        }
    
    }
    

      

    //测试类
    public class ProductConsumerTest {
    
        public static void main(String args[]){
            BookCase b = new BookCase();
            new Producer(b).start();
            new Consumer(b).start();
        }
    }
    

      

  • 相关阅读:
    字符集转换
    基础语法
    python print格式化输出。
    错误:SyntaxError: Missing parentheses in call to 'print'
    delphi 线程教学第一节:初识多线程
    delphi 7 信息对话框的按钮屏蔽键盘操作,只允许鼠标点击
    delphi 7 下安装 indy 10.5.8 教程
    delphi 实现vip126发邮件
    delphi 基础书籍推荐
    delphi 编码速度提升技能
  • 原文地址:https://www.cnblogs.com/wangfg/p/10741772.html
Copyright © 2011-2022 走看看