• 自我实现消费者生产者实例


    //操作对象
    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();
        }
    }
    

      

  • 相关阅读:
    跨平台的图形软件Dia
    Marvel
    How to install Freemind 1.0.1 to Ubuntu 14
    PHP环境搭建
    java 调用wsdl接口同时将返回数据解析成json
    WSDL接口调用
    struts2 使用装饰页面 /decorators
    Android WebView中的JavaScript代码使用(转载)
    android WebView 显示网页
    linux vi 编辑器命令
  • 原文地址:https://www.cnblogs.com/wangfg/p/10741772.html
Copyright © 2020-2023  润新知