java.util.concurrent.blockingqueue
接口是queue
接口的子接口,另外还支持诸如在检索元素之前等待队列变为非空的操作,并在存储元素之前等待队列中的空间变得可用 。
序号 | 方法 | 描述 |
---|---|---|
1 | boolean add(e e) |
将指定的元素插入到此队列中,如果可以立即执行此操作,而不会违反容量限制,在成功时返回true ,并且如果当前没有空间可用,则抛出illegalstateexception 。 |
2 | boolean contains(object o) |
如果此队列包含指定的元素,则返回true 。 |
3 | int drainto(collection<? super e> c) |
从该队列中删除所有可用的元素,并将它们添加到给定的集合中。 |
4 | int drainto(collection<? super e> c, int maxelements) |
最多从该队列中删除给定数量的可用元素,并将它们添加到给定的集合中。 |
5 | boolean offer(e e) |
将指定的元素插入到此队列中,如果可以立即执行此操作而不违反容量限制,则成功返回true ,如果当前没有空间可用,则返回false 。 |
6 | boolean offer(e e, long timeout, timeunit unit) |
将指定的元素插入到此队列中,等待指定的等待时间(如有必要)才能使空间变得可用。 |
7 | e poll(long timeout, timeunit unit) |
检索并删除此队列的头,等待指定的等待时间(如有必要)使元素变为可用。 |
8 | void put(e e) |
将指定的元素插入到此队列中,等待空间/容量可用。 |
9 | int remainingcapacity() |
返回此队列可理想地(在没有内存或资源约束的情况下)接受而不阻止的附加元素数,如果没有内在限制则返回integer.max_value 。 |
10 | boolean remove(object o) |
从该队列中删除指定元素的单个实例(如果存在)。 |
11 | e take() |
检索并删除此队列的头,如有必要,等待元素可用。 |
以下testthread
程序显示了基于线程的环境中blockingqueue
接口的使用。
import java.util.random;
import java.util.concurrent.arrayblockingqueue;
import java.util.concurrent.blockingqueue;
public class testthread {
public static void main(final string[] arguments) throws interruptedexception {
blockingqueue<integer> queue = new arrayblockingqueue<integer>(10);
producer producer = new producer(queue);
consumer consumer = new consumer(queue);
new thread(producer).start();
new thread(consumer).start();
thread.sleep(4000);
}
static class producer implements runnable {
private blockingqueue<integer> queue;
public producer(blockingqueue queue){
this.queue = queue;
}
@override
public void run() {
random random = new random();
try {
int result = random.nextint(100);
thread.sleep(1000);
queue.put(result);
system.out.println("added: " + result);
result = random.nextint(100);
thread.sleep(1000);
queue.put(result);
system.out.println("added: " + result);
result = random.nextint(100);
thread.sleep(1000);
queue.put(result);
system.out.println("added: " + result);
} catch (interruptedexception e) {
e.printstacktrace();
}
}
}
static class consumer implements runnable {
private blockingqueue<integer> queue;
public consumer(blockingqueue queue){
this.queue = queue;
}
@override
public void run() {
try {
system.out.println("removed: " + queue.take());
system.out.println("removed: " + queue.take());
system.out.println("removed: " + queue.take());
} catch (interruptedexception e) {
e.printstacktrace();
}
}
}
}
这将产生以下结果 -
added: 73
removed: 73
added: 19
removed: 19
added: 47
removed: 47