【参考文章:】http://www.cnblogs.com/belen/archive/2012/04/13/2446019.html
BlockingQueue 定义了一个FIFO的队列接口,。试图向已满队列中放入元素会导致放入操作受阻塞;试图从空队列中检索元素将导致
类似阻塞。
ArrayBlockingQueue是此接口的一个实现。
API:http://www.ostools.net/uploads/apidocs/jdk-zh/java/util/concurrent/ArrayBlockingQueue.html
下面是一个例子: 两个线程,thread1, thread2, 各自维护队列queue1, queue2, 初始时queue2不阻塞, 之后两个 thread
在自己的queue中加入元素,在对方的queue中take元素,进行十次这样的操作。
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ArrayBlockingCommunication {
public static void main(String[] args) {
final Business bussiness = new Business();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
bussiness.methodForThread1(i);
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
bussiness.methodForThread2(i);
}
}
}).start();
}
static class Business {
BlockingQueue <Integer> queue1 = new ArrayBlockingQueue <Integer> (1);
BlockingQueue <Integer> queue2 = new ArrayBlockingQueue <Integer> (1);
{
try {
queue2.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void methodForThread1(int i) {
try {
queue1.put(1);
System.out.println("Thread " + Thread.currentThread().getName() + " is blocking");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + Thread.currentThread().getName() + " is running : " + i);
try {
queue2.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void methodForThread2(int i) {
try {
queue2.put(1);
System.out.println("Thread " + Thread.currentThread().getName() + " is blocking");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread " + Thread.currentThread().getName() + " is running : " + i);
try {
queue1.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}