Java Reference
In-Depth Information
System
.
out
.
println
(
"CONSUMER INTERRUPTED"
);
}
}
void
void
process
(
Object obj
) {
// Thread.sleep(123) // Simulate time passing
System
.
out
.
println
(
"Consuming object "
+
obj
);
}
}
ProdCons15
(
int
int
nC
) {
BlockingQueue
<
Object
>
myQueue
=
new
int
nP
,
int
new
LinkedBlockingQueue
<>();
for
for
(
int
int
i
=
0
;
i
<
nP
;
i
++)
new
new
Thread
(
new
new
Producer
(
myQueue
)).
start
();
for
for
(
int
int
i
=
0
;
i
<
nC
;
i
++)
new
new
Thread
(
new
new
Consumer
(
myQueue
)).
start
();
}
public
public static
static
void
void
main
(
String
[]
args
)
throws
throws
IOException
,
InterruptedException
{
// Start producers and consumers
int
int
numProducers
=
4
;
int
int
numConsumers
=
3
;
ProdCons15 pc
=
new
new
ProdCons15
(
numProducers
,
numConsumers
);
// Let the simulation run for, say, 10 seconds
Thread
.
sleep
(
10
*
1000
);
// End of simulation - shut down gracefully
pc
.
done
=
true
true
;
}
}
ProdCons15
is superior to the implementation in the previous recipe in almost all aspects.
However, the queue sizes that are output no longer necessarily exactly reflect the size of the
queue after the object is inserted or removed. Because there's no longer any locking ensuring
atomicity here, any number of queue operations could occur on other threads between thread
A's queue insert or removal, and thread A's queue size query.