Killing thread immediately

I want to kill a thread immediately -
I mean that it if I use the method interrupt() it's change a flag and it takes time until the thread recognize that he was interrupted. I want to kill the thread with minimum time.

Thanks
Yefi
yefigAsked:
Who is Participating?
 
JodConnect With a Mentor Commented:
There are a number of reasons why not to use stop. It is inherently unsafe due to the nature of concurrent programming. Full details are explained here:

http://java.sun.com/products/jdk/1.2/docs/guide/misc/threadPrimitiveDeprecation.html

The way you are stopping the thread currently is the safest way.

If you must use stop, then surround the point at twhich you start your thread with a

try {}
catch {}
finally {}

block so that you can interrupt the thread, stop it and then do any cleanup neccesary in the finally block of code. For example:

    try {

     scroller = new MyThread(...);
     scroller.start();
      // etc.

    } catch (Exceptions here) {

    } finally {

      // do cleanup here
   }


or something like that that fits how you are using the threads.

The finally block is guaranteed to execute after the try and catch blocks so you can safely assume that if you have stopped the thread you can sort out any issues in the code for this finally block.

Other options are to check your flag more often for example.

Concurrent programming is not easy and these issues will may be not seem important now, but if you are not careful you could affect the stability of your program. This will also depend on what the threadis actually doing and what resources it uses.

As a further note though, for applets the convention has been to create threads in init(), start them in start(), and stop them in stop():

public class MyApplet extends Applet {

   private MyThread scroller;

   public void init() {
      scroller = new MyThread(...);
      // etc.
   }

    public void start() {
      scroller.start();
      // etc.
   }

   public void stop() {
      scroller.stop();
      // etc.
   }

   // etc.
}
0
 
OviCommented:
stop() ?
0
 
mbormannCommented:
look at
http://web2.java.sun.com/docs/books/tutorial/post1.0/preview/threads.html

particularly look at this code,use the currentThread() method

public void run()
{
      Thread thisThread = Thread.currentThread();
      while (blinker == thisThread)
      {
            try
            {
                Thread.sleep(interval);
            }
            catch (InterruptedException e)
            {}
            repaint();
      }
}
0
 
Ravindra76Commented:

What a points 123??

:)
0
All Courses

From novice to tech pro — start learning today.