• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to stop a thread

 
jite eghagha
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an applet that searches for an item via linear, binary searches etc. It also executes heaps sorts, quick sorts etc. Eventually i will be using ALL its functions simultaneously.

I run each of the applets functions in a separate Thread.

I'd like to know the best way to stop a Thread when its function is completed.

I start my linear search thread here:



In my runnable class LnSearchThread, my run method is:



In my linearSearch method ends with a return like so:



After the linear search is completed i get my desired result, but the thread remains Alive.

How and where is the best place to stop the thread?

 
Paul Clapham
Sheriff
Posts: 21892
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The way for a thread to terminate itself when it has finished its work is simply to return from the run() method. And it appears your code does that, although there could be code you didn't show us which is an infinite loop of some kind.
 
jite eghagha
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm confident that there is no endless loop, all of my search and sort functions run and terminate correctly.

Here's what a full class looks like (not search or sort for brevity sake):



I create the Thread and call the start method,



and my result is this:
ButtonThread true
run() began in ButtonThread
run() ended in ButtonThread

Why is thread t still alive?
 
Paul Clapham
Sheriff
Posts: 21892
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
jite eghagha wrote:I create the Thread and call the start method,



and my result is this:
ButtonThread true
run() began in ButtonThread
run() ended in ButtonThread

Why is thread t still alive?


Because it hasn't finished running yet. It is completely unsurprising to find out that it's still active one micro-second after you start it.
 
jite eghagha
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you,

I inserted a little delay after the start method to confirm

 
Paul Clapham
Sheriff
Posts: 21892
36
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want your code to wait until that thread ends, then you just call the thread's join method:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!