美文网首页
生产者/消费者模式

生产者/消费者模式

作者: 迷糊小生 | 来源:发表于2019-03-30 20:57 被阅读0次
    public class ValueObject {
    
        public static String value = "";
    
    }
    
    //生产者
    public class Product {
    
        private String lock;
        
        public Product(String lock) {
            this.lock = lock;
        }
        
        public void setValue() {
            try {
                synchronized (lock) {
                    if(!ValueObject.value.equals("")) {
                        lock.wait();
                    }
                    String value = System.currentTimeMillis() + "_" + System.nanoTime();
                    System.out.println("set:" + value);
                    ValueObject.value = value;
                    lock.notify();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
    }
    
    //消费者
    public class Customer {
    
        private String lock;
        
        public Customer(String lock) {
            this.lock = lock;
        }
        
        public void getValue() {
            try {
                synchronized (lock) {
                    if(ValueObject.value.equals("")) {
                        lock.wait();
                    }
                    System.out.println("get:" + ValueObject.value);
                    ValueObject.value = "";
                    lock.notify();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
    }
    
    public class ThreadA extends Thread{
    
        private Product product;
        public ThreadA(Product product) {
            this.product = product;
        }
        
        @Override
        public void run() {
            while (true) {
                product.setValue();
                
            }
        }
    }
    
    public class ThreadB extends Thread {
    
        private Customer customer;
    
        public ThreadB(Customer customer) {
            this.customer = customer;
        }
    
        @Override
        public void run() {
            while (true) {
                customer.getValue();
            }
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            try {
                String lock = new String("");
                Product product = new Product(lock);
                ThreadA threadA = new ThreadA(product);
                threadA.start();
                Thread.sleep(1000);
                Customer customer = new Customer(lock);
                ThreadB threadB = new ThreadB(customer);
                threadB.start();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
        }
    }
    
    image.png

    相关文章

      网友评论

          本文标题:生产者/消费者模式

          本文链接:https://www.haomeiwen.com/subject/ioasbqtx.html