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


Java
package producerconsumer;

import java.util.Scanner;

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

    public Consumer(String name) {
        t = new Thread(this, name);
        t.start();
        
    }
    @Override
    public  void run() {
        int m = Producer_consumer.n;
        try {
            if (m!=0) {           
                 Producer_consumer.delay.acquire();
            }
            else
            {
                Thread.sleep(100); //??   
            }
            
            while (true) {
                Producer_consumer.criticalSection.acquire();
                consumerName = Thread.currentThread().getName();
                consume();
                Producer_consumer.n--;
                Producer_consumer.form.setLable(Producer_consumer.n + "");
                m = Producer_consumer.n;
                Producer_consumer.criticalSection.release();

            }

        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }

    }

    }
Posted
Updated 12-Jan-15 10:02am
v2
Comments
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.
—SA

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: http://www.javamex.com/tutorials/threads/stopping_thread.shtml[^].

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

—SA
 
Share this answer
 
v2

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