headermask image

header image

Java Concurrent Blocking Queue

前两天公司培训RTSJ说到了JDK1.5的conccurrent包,
这个包中确实增加了不少实用类。课堂上面说到了

这个精简的阻塞工作队列,感觉很实用

//这个例子示例了使用阻塞队列协调生产者和消费者的关系,当有一些工作需要做的时候,生产者向队列中增加工作单元。消费者多
//线程消费。重点在于当队列满的时候生产者向队列中增加这个动作阻塞。


// Create a bounded blocking queue of integers
final int capacity = 10;
BlockingQueue queue = new ArrayBlockingQueue(capacity);
// Create a set of worker threads
final int numWorkers = 2;
Worker[] workers = new Worker[numWorkers];
for (int i=0; i workers[i] = new Worker(queue);
workers[i].start();
}try {
// Add some work to the queue; block if the queue is full.
// Note that null cannot be added to a blocking queue.
for (int i=0; i<100; i++) {
queue.put(i);
}// Add special end-of-stream markers to terminate the workers
for (int i=0; i queue.put(Worker.NO_MORE_WORK);
}
} catch (InterruptedException e) {
}This worker thread removes an integer from the work queue and calculates its square.
class Worker extends Thread {
// Special end-of-stream marker. If a worker retrieves
// an Integer that equals this marker, the worker will terminate.
static final Integer NO_MORE_WORK = new Integer(0);BlockingQueue q;

Worker(BlockingQueue q) {
this.q = q;
}
public void run() {
try {
while (true) {
// Retrieve an integer; block if the queue is empty
Integer x = q.take();

// Terminate if the end-of-stream marker was retrieved
if (x == NO_MORE_WORK) {
break;
}

// Compute the square of x
int y = x * x;
}
} catch (InterruptedException e) {
}
}
}

If you liked my post, feel free to subscribe to my rss feeds

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*