Java实现生产者、消费者的几种方法

先说下同步原语。

我们假设有两个信号量full(表示slots中有货),empty(表示slots中有空闲)

生产者:

producer:

wait(empty)

mutex_lock

put an item

mutex_unlock

signal(full)

消费者:

consumer:

wait(full)

mutex_lock

get an item

mutex_unlock

signal(empty)

上述同步原语很古董了,Java中很难有这些直接的翻译方法(pthread_mutext还是有的)。

Java中实现生产者、消费者模型有N多方法,本文主要介绍如下几种:

1、synchronized同步对象,下述代码只适合单生产者、单消费者。

import java.util.LinkedList;

class Producer implements Runnable {

	public Producer(LinkedList<Integer> slots) {
		this.slots = slots;
	}

	public void run() {
		while (true) {
			synchronized (slots) {
				try {
					// wait(empty)
					while (slots.size() >= PCV1.MAX) {
						slots.wait();
					}
					// put
					if (slots.add(new Integer(cnt))) {
						System.out.println("Producer : " + cnt);
						cnt++;
						slots.notify();
					}
				} catch (Exception e) {

				}
			}
		}
	}

	private LinkedList<Integer> slots = null;
	private int cnt = 0;
}

class Consumer implements Runnable {

	public Consumer(LinkedList<Integer> slots) {
		this.slots = slots;
	}

	public void run() {
		while (true) {
			synchronized (slots) {
				try {
					// wait(full)
					while (slots.size() == 0) {
						slots.wait();
					}
					// get
					System.out.println("Consumer : " + slots.removeFirst());
					slots.notify();
				} catch (Exception e) {

				}
			}
		}
	}

	private LinkedList<Integer> slots = null;
}

public class PCV1 {
	public static final int MAX = 10;

	public static void main(String[] args) {
		LinkedList<Integer> slots = new LinkedList<Integer>();
		Thread t1 = new Thread(new Producer(slots));
		Thread t2 = new Thread(new Consumer(slots));
		try {
			t1.start();
			t2.start();
			t1.join();
			t2.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *