abacaba
abacaba

Reputation: 9

Trying to stop thread, but it start again

Hi I'm using the next code to try to stop a thread, but when I see that Running is false it becomes true again.

public class usoos {
    public static void main(String[] args) throws Exception {
        start();
        Thread.sleep(10000);
        end();
    }

    public static SimpleThreads start(){
        SimpleThreads id = new SimpleThreads();
        id.start();
        System.out.println("started.");
        return id;
    }

    public static void end(){
        System.out.println("finished.");
        start().shutdown();
    }
}

And the thread

public class SimpleThreads extends Thread {
    volatile boolean running = true;

    public SimpleThreads () {
    }

    public void run() {         
        while (running){
            System.out.println("Running = " + running);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {}
        }
        System.out.println("Shutting down thread" + "======Running = " + running);
    }

    public void shutdown(){
        running = false;
        System.out.println("End" );
    }
}

The problem is that when I try to stop it(I set running to false), it starts again..

Upvotes: 0

Views: 76

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200168

Look at this line in the end method:

start().shutdown();

You are not stopping the original instance; you are starting another one, which you then immediately shut down.

There is no connection between your start and end methods—no information, no reference is passed from one to the other. It is obviously impossible to stop the thread you started in the start method.

Your end method should not be static; in fact, you don't even need it, shutdown is already it:

SimpleThreads t = start();
Thread.sleep(10000);
t.shutdown();

Upvotes: 5

shem
shem

Reputation: 4712

Because in the end method you just create a new Thread and kill it, save the thread instance and kill it:

Your code should look something like this:

public class usoos {
public static void main(String[] args) throws Exception {
    SimpleThreads id = start();
    Thread.sleep(10000);
    end(id);
}

public static SimpleThreads start(){
    SimpleThreads id = new SimpleThreads();
    id.start();
    System.out.println("started.");
    return id;
}

public static void end(SimpleThreads id){
    System.out.println("finished.");
    id.shutdown();
}

Upvotes: 0

Related Questions