简体   繁体   中英

Thread not stopping in this code,any reason?

Why in this code after the completion of consumer thread,producer thread is not interrupted,that is its flow is not stopping?

class buffer{
    int value;
    public void consume()
    { 
        System.out.println(value+" is consumed");

    }
    public  void produce(int x)
    {

        value=x;
        System.out.println(value+" is produced");


    }


}
class producer extends Thread
{
    buffer x;

    public producer(buffer x)
    {
        this.x=x;
    }
    public void run()
    {
        for(int i=0;i<15;i++)
        {
            x.produce(i);

        }

    }
}
class consumer extends Thread
{
    buffer x;
    producer y;

    public consumer(buffer x,producer y) {
        super();
        this.x = x;
        this.y=y;
    }

    public void run()
    {
        for(int i=0;i<10;i++)
        {
            x.consume();
        }
        y.interrupt();
    }
}
class tester
{
    public static void main(String[] args) {

        buffer x=new buffer();
        producer z=new producer(x);
        consumer y=new consumer(x,z);
        y.start();
        z.start();
    }   
}

As the Java tutorial on Thread interruption here states

It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

You have not specifically done anything to handle interruption so nothing happens when you invoke

y.interrupt();

The way I would have done this is by implementing Runnable

Eg:

public class producer implements Runnable{

buffer x;

public producer(buffer x){
    this.x=x;
}

@Override
public void run(){
    for(int i=0;i<15;i++){
        x.produce(i);
    }

}

And when you want to stop the Thread you can simply use the code [THREAD TO STOP].join();

EG producerThread.join();

The join method waits for the thread to stop safely but not instantly BUT you could use [THREAD TO STOP].stop() the only problem is that it can cause other problems depending on what you need it for. Only use it if you NEED the program to stop then and there!

extending Thread won't work because you're trying to make the class itself a thread. All though you will need to create a new Thread variable and set it to the class to become a thread but it is easy enough.

I don't see why these would even need to be a Thread any way, shouldn't it work with it running one after each other?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM