1
Hello!
I’m starting to use BlockingQueue
and ExecutorService
to implement a Producer-Consumer.
Looking at the page https://is.gd/BcIIXK, I removed line 24, and changed line 38 to Thread.sleep(3000);
, for the producer to be faster than the consumer.
But the result was:
Produced 0
Produced 1
Produced 2
Consume 0
Consume 1
Produced 3
Consume 2
Produced 4
Consume 3
Produced 5
Consume 4
Produced 6
That is, after the consumer ran the first time, both he and the producer stopped by the same Sleep.
Reading the help of ExecutorService::execute
, we have:
Executes the Given command at some time in the Future. The command may execute in a new thread, in a pooled thread, or in the Calling thread, at the discretion of the Executor implementation.
It seems that both producerTask
and consumerTask
are running in the same thread.
Someone would know how to force them to run on separate threads, so that the production speed is, in fact, different from that of consumption?
Thank you
The two are running on the same thread is not possible because the two are looped. It is two loops for a thread to only run at the same time, it is not possible. You can print the threads names (
Thread.currentThread().getName()
) to make sure that.– Piovezan
Only suggestions given above, try switching to a blocking queue that does not have a fixed size or increase the capacity of the blocking queue. Search the classes that implement the interface
BlockingQueue
. Print thesize()
of the queue can also help understand what happens.– Piovezan
Just remembering that as its name says the queue is blocking, ie when you try to do
put(item)
(oradd(item)
, do not remember) with it full orpoll()
with it empty she blocks until she is able to meet the request.– Piovezan
It seems the second suggestion explains
– canellas