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();
        }
    }
    

      

  • 相关阅读:
    DIV指令一般用法
    "Programming"和"Programming"是同一个"Programming"吗?
    对5个国家的名称进行排序详细解析
    Hello World程序
    用 select 实现多选
    浅谈HTTP中Get与Post的区别
    ligerUI 下拉框表格(多选)
    LigerUI自带弹窗返回值例子
    LigerUI Grid服务端分页技术
    jQuery LigerUI 插件介绍及使用之ligerGrid
  • 原文地址:https://www.cnblogs.com/wangfg/p/10741772.html
Copyright © 2011-2022 走看看