• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

killing a Thread ?

 
Ranch Hand
Posts: 1491
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How to kill active thread using java.util.Concurrent package ?
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you are working with Thread on the low level than the usual implementation is to override interrupt in your Thread an set a boolean flag to true. Within the run method you implement various checks if that variable was set to true and hence quit the run method.
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

kri shan wrote:How to kill active thread using java.util.Concurrent package ?



Do you mean using the ExecutorServices? Can you describe exactly what you want to do?

If you wanted to kill a particular task submitted to an ExecutorService then you would use the Future generated by the executor. The task you put into an ExecutorService are Runnables. Make the Runnables respond to interruption by checking the Thread.currentThread.isInterrupted() or Thread.interrupted() methods (ie, if one returns true, the task stops working, cleans up, and returns). You would then take the Future object the ExecutorService generated and call tasksFuture.cancel(true) on it.

If you want to cancel all tasks / threads running on an executor then you should make sure your tasks respond to interruption as above, and then you can call ExecutorService#shutdown().

If you want to make sure that the ExecutorService kills its Threads when all tasks are complete, then call the ExecutorService#shutdown() method after submitting all your tasks, or provide a ThreadFactory to the executor that generates Daemon threads so they shutdown automatically when the application completes.
 
reply
    Bookmark Topic Watch Topic
  • New Topic