i have this scenario:
class MyClass {
Producer p;
Consumer c;
public static void main(String[] args){
BlockingQueue q = new LinkedBlockingQueue();
p = new Producer(q);
c = new Consumer(q);
Thread t = new Thread(p);
t.start();
new Thread(c).start();
while (true) {
if (!p.getContinuer()) {
c.setContinuer(false);
System.out.println("here:"+p.getContinuer().toString());
break;
}
}
System.out.println("finish all");
}
}
class Producer implements Runnable {
private final BlockingQueue queue;
private AtomicBoolean continuer = new AtomicBoolean(true);
public Boolean getContinuer() {
return continuer.get();
}
@Override
public void run() {
while(true){
//open socket
//read data from socket
queue.put(data);
if(end){
System.out.println("Shutting down Producer");
continuer.getAndSet(false);
}
}
}
}
class Consumer implements Runnable {
private final BlockingQueue queue;
private static AtomicBoolean continuer = new AtomicBoolean(true);
public void setContinuer(Boolean continuerr) {
continuer = new AtomicBoolean(continuerr);
}
public Boolean getContinuer() {
return continuer.get();
}
@Override
public void run() {
while (getContinuer()) {
//Do some work
consume(queue.take());
}
System.out.println("shut down Consumer");
}
}
this is what i’m getting:
Shutting down Producer
here:false
finish all
that means that the consumer still working, and the variable “continuer” isin’t updated.
i saw also this and this posts, i tried it, but nothing changed.
what’s my problem ?
EDIT: i changed my code, and apparently the consumer is blocked (waiting if no elements are present on this queue. ) when trying to read data from the BlockingQueue (see consume(queue.take()); in the consumer class).
Well,
Looks wrong. Why don’t you
Furthermore, if the
endvariable is not volatile, it may be cached in threads.We will need to see more code. (Or at least compiling code.) Because this code works as expected:
It prints
Regarding your edit:
You should, after your
c.setContinuer(false);doconsumerThread.interrupt(). The consumer thread that’s blocked in thereadmethod, will throw an InterruptedException, (which you may ignore), and then exit the loop and terminate gracefully.