How can I kill a thread? without using stop();
please help me
peter
Printable View
How can I kill a thread? without using stop();
please help me
peter
When I want to kill a thread I create a method that when I call it, it prepares the thread to kill it
check this code, and if you have doubts, tell me
byeCode:boolean finish = false;
void run(){
while(!finish ){
//process
}
//clean resources
}
public void finish Thread(){
this.finish = true;
}
check if it is useful to you:
Code:class Example implements Runnable {
Thread t;
Object runLock = new Object();
volatile boolean shouldRun = false;
public void start() {
if (t == null) {
shouldRun = true;
t = new Thread(this);
t.start();
}
else {
synchronized(runLock) {
shouldRun = true;
runLock.notify();
}
}
} // end start
public void stop() {
shouldRun = false;
} // end stop
public void run() {
for (;;) {
synchronized(runLock) {
while (shouldRun == false)
try {
runLock.wait();
} catch (InterruptedException ie) {
}
}
}
} // end run
}
You can call Thread.interrupt(). But this does not mean that the thread will stop simultaneously. Read javadoc about how to use it.
how can i call finish method ?in the explanation of Heather
That wasn't the point of his post. He's trying to say that you should make a method that sets a variable (let's call this variable stopNow) true while the thread you want to stop is running. In that thread, have all the process in a while loop that checks if stopNow is true or false. If it's true, get out of the while loop; thus, the process is terminated. However, the code has to be iterative.
the run method can have this structure
Code:public void run() {
while(!isInterrupted()) {
// doStuff
try {
} catch (InterruptedException ex) {
interrupt();
}
}
now, when you instantiate your thread and start it it will runs for ever until you call the method interrup() on your instance. this will cause the InterrupedException so that inside the run-method the catch-block will be executed and the interrupt() inside the catch-block will stop the while loop! a small example
Code:public class RunningThread implements Runnable {
long start = System.currentTimeMillis();
public void run() {
while (!Thread.currentThread().isInterrupted()) {
;
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
System.out.println("RunningThread InterruptedException");
System.out.println("running time in millis: "
+ (System.currentTimeMillis() - start));
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
RunningThread rt = new RunningThread();
Thread t = new Thread(rt);
// start the RunnableThread,
// set the current main thread to sleep for 2 secs or 2000 millis
// and then stop the RunnableThread
t.start();
try {
Thread.sleep(2000);
t.interrupt();
} catch (InterruptedException ex) {
}
}
}