0

I have a Class which implements Runnable. I am using this Class in a thread and am trying to pause it and then restart it again using some sort of a boolean flag. This is my code:

class pushFiles implements Runnable{    
    private volatile boolean running = true;

    public void run () {
        .
        .  some code
        .
        while (running){
            .
            .  more code
            .
        }
    }

    public void stop() {
        running = false;
    }

    public void start() {
        running = true;
    }
};

I am trying to pause the thread using the stop method and restart it using the start method.

The stop method actually stops/pauses the thread, but the start method does not make it run again.

When initializing the thread I use:

runnable = new pushFiles();
thread = new Thread(runnable);
thread.start();

What am I doing wrong? Is it possible to unpause a thread? How can I do it?

River
  • 8,031
  • 13
  • 51
  • 64
  • 3
    If you set `running` to false you actually don´t pause the execution, your `while` loop will end the the `Thread` has finished it´s execution. Sidenode: please follow the java naming convention and start classnames with uppercase letters. – SomeJavaGuy Jun 01 '16 at 10:01
  • so i just have to create a new thread for the same class? –  Jun 01 '16 at 10:15
  • 1
    @DanyLavrov See [this answer](http://stackoverflow.com/a/37565875/889583) to another, similar question. I've just posted it and based it on your code here. – daiscog Jun 01 '16 at 10:32

1 Answers1

3
while (running){
            .
            .  more code
            .
        }

so when running is false, your run() method will exit and your thread will be no more.

Here's an example of how to do what you want, using wait()/notify()

Brian Agnew
  • 261,477
  • 36
  • 323
  • 432