Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how to stop a running thread  RSS feed

 
zhengyw zhengyw
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in my project,i use thread to dispatch my request to the service in my contorller,and the process is synchronized,that is ,in my thread's run() body,call a service's method,maybe the method last for a long time,then the user of client application maybe cancel this request,so in the executing of a thread,how can i stop it and then return the thread to a vector?thanks
 
Pavel Halas
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I understand you, you would make the thread to stop using some user action (button click)...
You should create a boolean field that should be periodically checked. If the action is long-lasting, this could be combined with a process indication.
 
zhengyw zhengyw
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah,i want to do that,but i how can i implement that idea?may i have to check a boolean field in the every running code line of a thread?
 
Jason Kosowan
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys
Actually, there are mechanisms built into Java to do this kind of thing.
To stop a running thread, the class that stops the thread must call

But, this alone is not enough. Within the thread, I've successfully used the following in a method that is declared to throw InterruptedException.

Interspersing these calls at appropriate times within the thread (i.e. between critical operations) will give a responsive and safe way to stop and start things.
If you want to see this in action, my little open-source project Spiderfish uses this type of interruption with Swing/JFC.
Spiderfish Project
Hope this helps.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!