Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Correct way to stop thread inside its own run method?  RSS feed

 
Alan Smith
Ranch Hand
Posts: 185
Firefox Browser Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

What is the correct way to stop a thread inside its own run method? Is this possible? For example, the following does not work:



The output I get is something like this:


Any ideas?

Edit: using return; instead of getThread().interrupt(); works, but is probably not the correct way.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Exiting the run method using return is the preferred approach.

A search for "java thread life cycle" should find you some useful tutorials.

Bill
 
Piet Souris
Rancher
Posts: 1943
66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
and if you want to return when an interrupt is received, simply check for 'isInterrupted()',
for instance in line 25: for (int i = 0; i <= 10 && !isInterrupted(); i++) {...}

Greetz,
Piet
 
Alan Smith
Ranch Hand
Posts: 185
Firefox Browser Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the info guys. I will mark this resolved.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!