生产者/消费者模式

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();
        }
        
    }
}
生产者/消费者模式_第1张图片
image.png

你可能感兴趣的:(生产者/消费者模式)