Java多线程:新特性—同步容器

阻塞队列


阻塞队列是Java5线程新特性中的内容,Java定义了阻塞队列的接口java.util.concurrent.BlockingQueue

阻塞队列的概念是,一个指定长度的队列,如果队列满了,添加新元素的操作会被阻塞等待,直到有空位为止。

同样,当队列为空时候,请求队列元素的操作同样会阻塞等待,直到有可用元素为止。

有了这样的功能,就为多线程的排队等候的模型实现开辟了便捷通道,非常有用。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ArrayBlockingQueue;
/**
* 阻塞队列
*
*/
public class Test {
public static void main(String[] args) throws InterruptedException {
BlockingQueue bqueue = new ArrayBlockingQueue(10);
for (int i = 0; i < 20; i++) {
// 将指定元素添加到此队列中,如果没有可用空间,将一直等待(如果有必要)。
bqueue.put(i);
System.out.println("add to queue: " + i);
}
System.out.println("over...");
}
}

输出结果:

1
2
3
4
5
6
7
8
9
10
add to queue: 0
add to queue: 1
add to queue: 2
add to queue: 3
add to queue: 4
add to queue: 5
add to queue: 6
add to queue: 7
add to queue: 8
add to queue: 9

可以看出,输出到元素9时候,就一直处于等待状态,因为队列满了,程序阻塞了。

阻塞队列还有更多实现类,用来满足各种复杂的需求:
ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue,具体的API差别也很小。

阻塞栈


阻塞栈是Java6的新特性,对于阻塞栈,与阻塞队列相似。不同点在于栈是“后入先出”的结构,每次操作的是栈顶,而队列是“先进先出”的结构,每次操作的是队列头。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 阻塞栈
*
*/
public class Test {
public static void main(String[] args) throws InterruptedException {
BlockingDeque bDeque = new LinkedBlockingDeque(10);
for (int i = 0; i < 20; i++) {
// 将指定元素添加到此阻塞栈中,如果没有可用空间,将一直等待(如果有必要)。
bDeque.putFirst(i);
System.out.println("add to stack: " + i);
}
System.out.println("over...");
}
}

输出结果:

1
2
3
4
5
6
7
8
9
10
add to stack: 0
add to stack: 1
add to stack: 2
add to stack: 3
add to stack: 4
add to stack: 5
add to stack: 6
add to stack: 7
add to stack: 8
add to stack: 9

可以看出,输出到元素9时候,就一直处于等待状态,因为栈满了,程序阻塞了。