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,585
  • 14
  • 54
  • 67
  • 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
  • 268,207
  • 37
  • 334
  • 440
  • Your thread is already terminated – wake-0 Jun 01 '16 at 10:02
  • i only have one thread. if ill make it wait, which thread will use the notify method? –  Jun 01 '16 at 10:14
  • 1
    You have 2 threads, don't you ? This one and the one that instantiated and ran this thread – Brian Agnew Jun 01 '16 at 10:22
  • how do i get an instance of the thread of the main method? how do i declare it? i have tried `thread.wait();` but i am getting an error. –  Jun 01 '16 at 15:22