Click here to Skip to main content
15,947,389 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
this is my consumer class
I cant know how can I stop a thread until a product will be produced?
(the sleep seems not work sometimes)
please suggest me a way other than the blocking queue interface and sleep method

package producerconsumer;

import java.util.Scanner;

public class Consumer implements Runnable {
    Thread t;
    String consumerName;

    public Consumer(String name) {
        t = new Thread(this, name);
    public  void run() {
        int m = Producer_consumer.n;
        try {
            if (m!=0) {           
                Thread.sleep(100); //??   
            while (true) {
                consumerName = Thread.currentThread().getName();
                Producer_consumer.form.setLable(Producer_consumer.n + "");
                m = Producer_consumer.n;


        } catch (InterruptedException ex) {


Updated 12-Jan-15 10:02am
Sergey Alexandrovich Kryukov 12-Jan-15 16:49pm    
Why that Sleep here? This is the sure sign of doing something very wrong. (If it's just for demo, it's fine.)
Analyze your code for possible race conditions.

1 solution

It looks like your problem is stopping a thread asynchronously, by the initiative of some other thread (only this situation usually causes difficulties).
The whole thing is a controversial topic I don't want to discuss here. I a few words, I dislike how it's done in Java. Most people stop thread in a collaborative way, by using some member (Boolean "flag") which can polled by a thread to be stopped and set by a separate thread. Also, Thread.interrupt can be used, with, but with certain "buts". This is pretty well described in this article:[^].

Note that the technique of "queued condition" is mentioned in relation to the producer-consumer patters and the use of blocking queue.

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900