java多线程之生产者-消费者

Posted Mars.wang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程之生产者-消费者相关的知识,希望对你有一定的参考价值。

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.err.println("set"+"++++++++++++++++++++++");
                ValueObject.value=value;
                Thread.sleep(1000);
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Consumer {
    private String lock;

    public Consumer(String lock) {
        this.lock = lock;
    }

    public void getValue(){
        try {
            synchronized (lock) {
                if(ValueObject.value.equals("")){
                    lock.wait();
                }
                System.err.println("get"+"---------------------------");
                ValueObject.value = "";
                lock.notify();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class ThreadP extends Thread {
    private Product product;

    public ThreadP(Product product) {
        this.product = product;
    }

    @Override
    public void run() {
        while (true) {
            product.setValue();
        }
    }
}

public class ThreadC extends Thread{
    private Consumer consumer;

    public ThreadC(Consumer consumer) {
        this.consumer = consumer;
    }

    @Override
    public void run() {
        while (true) {
            consumer.getValue();
        }
    }
}

public class ValueObject {
    public static String value = "";
}

public class Test {
    public static void main(String[] args) {
        String lock=new String("");
        Product product = new Product(lock);
        Consumer consumer = new Consumer(lock);
        ThreadP p = new ThreadP(product);
        ThreadC c = new ThreadC(consumer);
        p.start();
        c.start();
    }
}

输出就是set和get交替打印

以上是关于java多线程之生产者-消费者的主要内容,如果未能解决你的问题,请参考以下文章

Java基础之多线程

Java多线程系列--“基础篇”11之 生产消费者问题

多线程之Java中的等待唤醒机制

Java多线程之生产者消费者问题<一>:使用synchronized keyword解决生产者消费者问题

java多线程之生产者-消费者

Java多线程系列-之生产消费者问题