top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to stop Thread in java 1.5

+1 vote
66 views
How to stop Thread in java 1.5
posted Oct 14, 2013 by Nagarajuk

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

+1 vote

Thread's stop(), suspend() etc., methods have been deprecated, the only way to safely terminate a thread is to have it exit its run() method, perhaps via an un-checked exception. In Sun's article, Why are Thread.stop, Thread.suspend and Thread.resume Deprecated? , there are some suggestions for how to stop a thread without using the unsafe deprecated methods.

The method suggested there is to use a volatile stop flag (blinker in the code below)

private volatile Thread blinker;
public void stop() {
    blinker = null;
}
public void run() {
    Thread thisThread = Thread.currentThread();
    while (blinker == thisThread) {
        try {
            thisThread.sleep(interval);
        } catch (InterruptedException e){
        }
        repaint();
    }
}

The volatile keyword is used to ensure prompt communication between threads. “A field may be declared volatile, in which case a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. Moreover, operations on the master copies of one or more volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested.” (See http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930 for more details.)

answer Oct 14, 2013 by Deepankar Dubey
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...