BlockingBuffer的使用:在操作对象前需要等待输入的情况要用到BlockingBuffer
Maven项目使用前,加入下述依赖在你的项目pom.xml中。
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
在多线程的情况下,才能验证BlockingBuffer,以下是一个简单的BlockingBuffer使用实例,主线程往BlockingBuffer中添加对象,而listenerThread则remove该对象,此时BlockingBuffer的作用显现,虽然listenerThread线程先一步启动,BlockingBuffer也会先等待对象的加入,再执行删除,故不会报错。
import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.buffer.BlockingBuffer;
import org.apache.commons.collections.buffer.BoundedFifoBuffer;
public class BufferTest {
public static void main(String[] args) {
/*
* Your system needs to wait for input and act on an object the moment it is
* added to a Buffer. To achieve this, you need your application to block until
* input is received, use BlockingBuffer to decorate an instance of Buffer.
* when a process calls get() or remove() on a buffer decorated with BlockingBuffer,
* the decorated buffer does not return a value until it has an object to return.
*/
//create a Blocking Buffer
Buffer buffer=BlockingBuffer.decorate(new BoundedFifoBuffer());
//Create Thread to continuously remove() from the previous Buffer
BufferListener listener=new BufferListener(buffer);
Thread listenerThread=new Thread(listener);
/*
* The listenerThread will block on a call to buffer.remove() within the run()
* method of BufferListener, an object that runs in a separate thread and
* waits for objects to be added to a BlockingBuffer.
*/
listenerThread.start();
buffer.add("Hello World!");
buffer.add("Goodbye,Y'all.");
}
}
BufferListner的实现:
import org.apache.commons.collections.Buffer;
/**
* a BlockingBuffer can only be demonstrated by an example
* that deals with multiple threads.BufferListener implements
* Runnable defined for this.
*
*
*/
public class BufferListener implements Runnable {
private Buffer buffer;
public BufferListener(Buffer buffer){
this.buffer=buffer;
}
@Override
public void run() {
while(true){
String message=(String)buffer.remove();
System.out.println(message);
}
}
}
结果如下:
Hello World!
Goodbye,Y'all.