0

Hello I want to make a if statement in JAVA, that..if thread is not running, we pressed a shortkey and the Thread start running, and if the thread is running, we pressed the same shortkey and the Thread stops running.

My code:

if(!th.isAlive()){
    th.start();
}else{
    th.stop();
    }

But doesn't work this code. Please help me.

p.s - This if statement happens when click in shortkey

Sandromedeiros
  • 367
  • 1
  • 4
  • 9
  • You should call interrupt() method to stop thread and catch InterruptedException. – Anton Kazakov Feb 27 '17 at 14:05
  • You should use interrupt(): http://stackoverflow.com/questions/3590000/what-does-java-lang-thread-interrupt-do – Andrey Feb 27 '17 at 14:06
  • 1
    stop() method is depricated. Method start() you can call only once. Use some boolean flag & wait/notify to stop/re-run your code or more convinient primitives from java.util.concurrent – rvit34 Feb 27 '17 at 14:08
  • doesn't work... – Sandromedeiros Feb 27 '17 at 14:12
  • Before you do anything with Threads, you need to read http://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#stop-- . If there are any deprecated methods which should be avoided at all costs, they would be Thread.stop, Thread.resume, and Thread.suspend. – VGR Feb 27 '17 at 15:47

1 Answers1

0

As mentioned above, you should use thread.interrupt() it is because the thread dies when calling stop() and thus cannot be restarted. (see How can a dead thread be restarted?)

You might be interested in CountDownLatch to implement the behavior you are describing.

Community
  • 1
  • 1
Adonis
  • 4,670
  • 3
  • 37
  • 57