首页 > 代码库 > java多线程基本概述(六)——简单生产者消费者模式

java多线程基本概述(六)——简单生产者消费者模式

  在线程里,生产者就是生产数据的线程,消费者就是消费数据的线程。在多线程开发当中,如果生产者处理速度很快,而消费者处理速度很慢,那么生产者就必须等待消费者处理完,才能继续生产数据。同样的道理,如果消费者的处理能力大于生产者,那么消费者就必须等待生产者。为了解决这个问题于是引入了生产者和消费者模式。下面实现一个简单的生产者消费者模式:

1.一个消费者一个生产者循环消费生产

package soarhu;

import java.util.ArrayList;
import java.util.List;

class Service{

    private final Object lock;
    private List<String> list = new ArrayList<>();

    public Service(Object lock) {
        this.lock = lock;
    }

    void waiting(){
        synchronized (lock){
                try {
                    while(list.size()==0){
                        lock.wait();
                    }
                    String value = list.remove(0);
                    System.out.println("consume: "+value);
                    lock.notifyAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        }
    }

    void notifying(){
        synchronized (lock){
            try {
                while(list.size()!=0){
                    lock.wait();
                }
                String value=System.currentTimeMillis()+"";
                list.add(value);
                System.out.println("produce: "+value);
                lock.notifyAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


public class Test {
    public static void main(String[] args) throws InterruptedException {
            Object o = new Object();
            Service service = new Service(o);
            for (int i = 0; i < 1; i++) {  //这里的数量为1
                new Thread(){
                    @Override
                    public void run() {
                        while (true) {
                            service.notifying();
                        }
                    }
                }.start();
            }
            Thread.sleep(1000);
            for (int i = 0; i < 1; i++) { //此时数量改为1
                new Thread(){
                    @Override
                    public void run() {
                        while (true) {
                            service.waiting();
                        }
                    }
                }.start();
            }
    }
}

输出结果

produce: 1492495274866
consume: 1492495274866
produce: 1492495274866
consume: 1492495274866
produce: 1492495274866
consume: 1492495274866
produce: 1492495274866
consume: 1492495274866
produce: 1492495274866
consume: 1492495274866
produce: 1492495274866
consume: 1492495274866
produce: 1492495274866
consume: 1492495274866
produce: 1492495274866
consume: 1492495274866
produce: 1492495274866
consume: 1492495274866
produce: 1492495274866
consume: 1492495274866
produce: 1492495274866
consume: 1492495274866
..............
..........
.........

 

java多线程基本概述(六)——简单生产者消费者模式