Results 1 to 4 of 4
Thread: Stopping a thread
- 08-13-2010, 07:01 PM #1
Member
- Join Date
- May 2010
- Posts
- 9
- Rep Power
- 0
- 08-13-2010, 07:05 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,405
- Blog Entries
- 7
- Rep Power
- 17
The only safe way is to programmatically ask it to stop; of course the thread has to cooperate, i.e. there is no safe way to slice its throat and kill it. Your runnable method has to test, say, a boolean variable repeatedly and when it has been set to true (by another thread) it has to quit.
kind regards,
Jos
- 08-13-2010, 07:19 PM #3
Member
- Join Date
- May 2010
- Posts
- 9
- Rep Power
- 0
Stopping a thread
thanks for your reply Jos.
As u suggested that we should use the approach of having a boolean variable to stop a thread. The same approach is discussed at multiple places where use of volatile variable is recommended so that all threads should refer to the same copy. I understood this concept. But have one confusion .. Why volatile has to be used? Cant we achieve the same by using a static variable instead of volatile?
Thanks
- 08-13-2010, 07:57 PM #4
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,405
- Blog Entries
- 7
- Rep Power
- 17
If you want to stop everything at once a static condition variable would do; and yes, always make those variables volatile because a compiler might, and pay special attention to the verb 'might', optimize out the test for non volatile variables; basically your Runnable should look like this:
somewhere else in that class you have a (static) volatile boolean stop variable that can be set to true by another thread.Java Code:public void run() { while (!stop) { process(); // do real work here ... } }
kind regards,
Jos
Similar Threads
-
Stopping a .swf with java
By ercarls in forum New To JavaReplies: 2Last Post: 04-14-2010, 06:33 PM -
stopping second time round
By silverspoon34 in forum New To JavaReplies: 0Last Post: 11-20-2009, 02:04 PM -
Pong Paddle Not Stopping Ball At Certain Speed
By JDCAce in forum Java AppletsReplies: 3Last Post: 04-01-2009, 11:07 PM -
Stopping a running thread in a multithreaded environment
By SUSHMA50 in forum Advanced JavaReplies: 11Last Post: 01-26-2009, 12:22 AM -
stopping thread...using flags
By rstepler in forum New To JavaReplies: 1Last Post: 07-31-2008, 09:36 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks