Skip to main content

How to Stop Thread in Java

 

Methods for Stopping a Thread

 
 
private volatile Thread thrd;
    public void stop() {
        thrd = null;
    }
    public void run() {
        Thread thisThread = Thread.currentThread();
        while (thrd == 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 as 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.” 

Comments