`
地球小野花
  • 浏览: 163159 次
  • 性别: Icon_minigender_1
  • 来自: 马赛大回旋
社区版块
存档分类
最新评论

生产者和消费者问题(BlockingQueue Implement)

阅读更多

Introduce BlockingQueue:

 

BlockingQueue only support java 1.5 or higher,and it's defined as below.

 

public interface BlockingQueue<E>
extends
Queue<E>

 

As the definition,the parameters E is the type of elements helding in this collection. A Queue that  additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

 

Summay of BlockingQueue methods:(as the figure)

 

 

  Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() not applicable not applicable

Pls Note: A BlociingQueue does not accept null elements. Implementations throw nullPointerException on attempts to add, put or offer a null. A null is used as a sentinel value to indicate failure of poll operations.

 

Primarily designed of BlockingQueue:

 

BlockingQueue implementations are designed to be used primarily for producer-comsumer queues, but addtionally support the Collection interface. So,for example, it is possiable to remove an arbitrary element from a queue using remove(i). However, such operations are in general not performed very efficiently, and are intended for only occasional use, such as when a queued message is cancelled.

 

Of course BlockingQueue implementations are thread-safe. All queeing methods achieve their effects atomically using internal locks or other form of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example for addAll(c) to fail (throw an exception) after adding only some of the elements in c.

 

Sample of use BlockingQueue to implement Producer-Consumer Question :

 

1. Create a producer.

Producer.java

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {

	private BlockingQueue queue;

	// put producer in queue
	public Producer(BlockingQueue q) {
		this.queue = q;
	}

	public void run() {
		try {
			while (true) {
				// wait for a random time
				Thread.sleep((int) (Math.random() * 3000));
				queue.put(produce());
			}
		} catch (InterruptedException ex) {
			// catch exception
		}
	}

	public String produce() {
		List<String> product = new ArrayList<String>();
		String producProduct = null;
		product.add("Car");
		product.add("Phone");
		product.add("Plane");
		product.add("Computer");
		boolean flag = true;
		int getProduct = (int) (Math.random() * 3);
		while (flag) {
			if (getProduct <= product.size()) {
				producProduct = product.get(getProduct);
				flag = false;
			}
		}
		System.out.println("Producer producing " + producProduct);
		return producProduct;
	}

}

 

2.Create a consumer.

Consumer.java

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable {

	private  BlockingQueue queue;

	public Consumer(BlockingQueue q){
		this.queue=q;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while (true) {
				// wait for a random time
				Thread.sleep((int) (Math.random() * 3000));
				consume(queue.take());
			}
		} catch (InterruptedException ex) {
		}

	}

	public void consume(Object x) {
		System.out.println("Consumer buy product "+x.toString());
	}
}

 

3. Test Client

TestClient.java

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;


public class TestClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new TestClient();
	}

	public TestClient() {
		BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(1);
		Thread producerThread = new Thread(new Producer(queue));
		Thread consumerThread = new Thread(new Consumer(queue));
		producerThread.start();
		consumerThread.start();
	}
}

 

 

 Summay:

 This sample introduces BlockingQueue Class and using it to implement the Producer-Consumer  Question.

 

  

 

2
0
分享到:
评论

相关推荐

    java模拟生产者和消费者问题

    尽管代码未完整展示逻辑部分,但可以看出其意图是通过按钮点击事件来模拟生产者生产数据和消费者消费数据的过程,从而可视化地演示阻塞和唤醒机制。 ### 总结 生产者-消费者问题不仅是并发编程的核心概念,也是...

    生产者和消费者问题以及哲学家就餐问题,JAVA实现的程序.rar

    在"生产者和消费者问题.txt"文件中,可能包含了使用`BlockingQueue`实现生产者消费者问题的Java代码示例,包括如何创建队列,以及生产者和消费者线程如何交互。而"哲学家就餐问题.txt"文件可能展示了如何用Java的...

    生产者和消费者模式多线程

    生产者和消费者模式是多线程编程中一个经典的设计模式,它主要解决的是在多线程环境下资源的有效利用和同步问题。在这个模式中,生产者负责生成数据,而消费者负责消费这些数据。为了保证生产与消费的平衡以及避免...

    java多线程实现生产者和消费者

    生产者和消费者线程都需要有自己的业务逻辑,这可以通过重写`run()`方法实现。 2. **共享资源**:在生产者-消费者模型中,通常会有一个固定大小的缓冲区作为共享资源。可以使用数组或链表实现,但需要注意的是,当...

    操作系统生产者与消费者问题Java简单模拟实现

    此外,`wait()`和`notify()`方法可能被用来在生产者和消费者之间进行更精细的控制。当生产者发现队列已满,它会调用`wait()`,将自身置于等待状态,同时释放锁。消费者取走元素后,如果发现队列为空,也会调用`wait...

    java 编写的生产者与消费者问题

    生产者和消费者在各自的线程中运行,通过调用`BlockingQueue`的`put`和`take`方法进行交互。 5. **死锁避免**: 在实现生产者-消费者问题时,必须注意死锁的可能。例如,如果生产者在放入元素前先等待消费者消费,而...

    java 生产者消费者问题(源码)

    为了解决生产者和消费者之间可能出现的同步问题,我们通常会引入一个缓冲区,用于存放生产者生产的产品,供消费者消费。 生产者消费者问题的关键在于确保以下几点: 1. **互斥**:当缓冲区满时,生产者必须停止生产...

    java生产者与消费者问题

    在这个例子中,生产者和消费者通过`BlockingQueue`进行交互。当队列满时,`put()`方法会使生产者线程暂停;队列空时,`take()`方法会使消费者线程暂停。这样就避免了生产者过度生产导致缓冲区溢出,以及消费者无产品...

    JAVA实现线程间同步与互斥生产者消费者问题

    生产者消费者问题是经典的并发问题之一,它涉及到两个类型的线程:生产者和消费者。生产者负责生成数据(产品),而消费者则负责消费这些数据。关键在于,生产者不应在没有消费者准备接收的情况下生成数据,同时消费...

    生产者与消费者 java实现

    Java中解决这一问题的关键类是`java.util.concurrent`包下的`BlockingQueue`接口,它提供了线程安全的队列操作,如`put()`和`take()`方法,分别用于生产者放入产品和消费者取出产品。当队列满时,`put()`会阻塞生产...

    java生产者消费者问题

    为了解决生产者和消费者之间的问题,Java提供了一系列的同步机制,如synchronized关键字、wait()、notify()和notifyAll()方法,以及高级的BlockingQueue接口。 首先,我们要理解生产者消费者模型的基本概念。在该...

    生产者消费者问题

    生产者消费者问题中,线程池可以用来管理生产者和消费者线程,避免频繁创建和销毁线程带来的开销。线程池有核心线程数、最大线程数、线程空闲时间、任务队列等参数,合理配置这些参数对于优化性能至关重要。 下面,...

    生产者消费者演示程序

    这个问题的核心在于如何有效地协调生产者和消费者,确保数据的生产和消费是有序且不会出现数据丢失或溢出的情况。 在计算机编程中,生产者消费者模型通常通过使用队列(Queue)数据结构来实现。队列是一种先进先出...

    Java 生产者消费者模式

    - **中介者类(Mediator)**:监控`BlockingQueue`状态,协调生产者和消费者的活动,可能包含`startProducer()`和`startConsumer()`等方法。 - **主程序(Main)**:初始化生产者、消费者和中介者对象,启动它们的...

    线程同步--生产者消费者问题

    生产者消费者问题是这样的:一个系统有两个主要的角色,生产者和消费者。生产者负责创建或生成数据,而消费者则消费这些数据。关键在于确保生产者不会在消费者还没有处理完当前数据时生成新的数据,同时消费者也不会...

    消费者与生产者问题

    消费者与生产者问题是多线程编程中的一个经典案例,它主要涉及到线程间...综上所述,消费者与生产者问题是理解线程同步和协作的关键实例,通过学习和实践这一问题,我们可以更好地掌握Java并发编程中的核心概念和技术。

    生产者消费者

    `Executors.newFixedThreadPool(2)`创建了一个包含两个线程的线程池,分别用于执行生产者和消费者任务。 通过这种方式,我们可以构建一个高效、线程安全的生产者消费者系统。在实际应用中,生产者消费者模式可以...

    生产者与消费者问题

    在生产者与消费者问题中,当生产者和消费者访问共享资源时,需要通过`synchronized`保证同一时间只有一个线程在操作。 4. **Lock接口**:比`synchronized`更灵活,提供了更多的控制。`Lock.lock()`用于获取锁,`...

    java线程实现的生产者和消费者的程序

    生产者消费者问题是并发编程中的一个基础模型,它描述了两个线程——生产者和消费者——如何协作共享一个有限的缓冲区。生产者负责生成数据并放入缓冲区,而消费者则从缓冲区取出数据进行消费。为避免生产者过度填充...

Global site tag (gtag.js) - Google Analytics