Consumer Producer Beispiel mit Java 5.0

Thomas Darimont

Erfahrenes Mitglied
Hallo!

Hier mal ein Beispiel zum bekannten Produzenten Konsumenten "Problem"
realisiert mittels einer ArrayBlockingQueue aus dem neuen java.util.Concurrent package:
Code:
/*
 * Created on 31.12.2004@17:10:51
 *
 * TODO Licence info
 */
package de.tutorials;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author Administrator
 * 
 * TODO Explain what I do...
 */
public class ProducerConsumerExample {

	private ArrayBlockingQueue queue = new ArrayBlockingQueue(10);

	public static void main(String[] args) {
		new ProducerConsumerExample().run();
	}

	private void run() {
		Thread producer = new Thread() {
			public void run() {
				while (true) {
					if (queue.remainingCapacity() > 0) {
						String str = String.valueOf(System.currentTimeMillis());
						System.out.println("Producer produced: " + str);
						queue.add(str);
					} else {
						System.out.println("queue is full producer waits...");
					}
					try {
						sleep(500L);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};

		Thread consumer = new Thread() {
			public void run() {
				while (true) {
					String str = (String) queue.poll();
					System.out.println("Consumer consumes: " + str);
					try {
						sleep(1500L);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};

		producer.start();
		consumer.start();

	}
}

Gruß Tom
 
Zurück