0

I searched at the Internet about stopping a thread. I could only find a deprecated method and a while method which doesn't really work.

My idea is declaring a custom exception and putting a try in the thread so I can stop that thread by throwing the exception.

Is my idea non-sense and is that why I can't find an answer like this on the Internet?

MCCCS
  • 1,002
  • 3
  • 20
  • 44
  • 2
    It's unclear what you're proposing, but surely you can try it for yourself. – Jon Skeet Dec 06 '16 at 14:04
  • 3
    Throwing an exception only affects the current thread, not a different thread. There is no cross-thread magic involving exceptions. Your Idea won't work. – Erich Kitzmueller Dec 06 '16 at 14:05
  • 1
    Possible duplicate of [How to properly stop the Thread in Java?](http://stackoverflow.com/questions/10961714/how-to-properly-stop-the-thread-in-java) – Tschallacka Dec 06 '16 at 14:05
  • 2
    Why a custom exception when there is the [InterruptedException built in](https://docs.oracle.com/javase/8/docs/api/java/lang/InterruptedException.html) – Gimby Dec 06 '16 at 14:08

1 Answers1

1

See this question:

When does a Java Thread reach the 'Die' State

(Among others) a thread dies if an exception is thrown that propagates beyond the run method.

So yes, you can throw some runtime exception from within your run method make sure you don't catch it anywhere in your thread, this will kill your thread.

Community
  • 1
  • 1
lexicore
  • 42,748
  • 17
  • 132
  • 221