Java Reference
In-Depth Information
One caveat is that, in real life, you generally would not want to perform I/O while holding
the monitor lock, because doing so is bad for performance.
Simplifying Producer/Consumer with the Queue Interface
Problem
You need to control producer/consumer implementations involving multiple threads.
Solution
Use the
Queue
interface or the
BlockingQueue
subinterface.
Discussion
As an example of the simplifications possible with
java.util.Concurrent
package, con-
sider the producer/consumer program in
Synchronizing Threads the Hard Way with wait( )
(itself a subinterface of the
java.util.Queue
interface) to reimplement the program
ProdCons2
from
Example 22-13
in about two-thirds the number of lines of code. With these
new features, the application need not be concerned with
wait()
or the vagaries of
noti-
fy()
and the use of
notifyAll()
in its place.
The application simply puts items into a queue and takes them from it. In the example, I have
(as before) four producers and only three consumers, so the producers eventually wait. Run-
ning the application on one of my older notebooks, the producers' lead over the consumers
increases to about 350 over the 10 seconds or so of running it.
Example 22-14. ProdCons15.java
public
public class
class
ProdCons15
ProdCons15
{
protected
protected volatile
volatile
boolean
boolean
done
=
false
false
;
/** Inner class representing the Producer side */
class
class
Producer
Producer
implements
implements
Runnable
{
protected
protected
BlockingQueue
<
Object
>
queue
;