Thread Step
In this chapter you will learn:
Stop a Java thread
The stop method from Thread
is deprecated.
In order to stop a thread we have to use a boolean
variable or similar
logic to exit a thread.
The following code uses the boolean value to control when
to stop a thread. The while
loop checks a boolean
variable.
If the condition doesn't meet it will keep loop and in that way we
make the thread alive.
class CounterThread extends Thread {
public boolean stopped = false;
//jav a 2 s. c om
int count = 0;
public void run() {
while (!stopped) {
try {
sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(count++);
;
}
}
}
public class Main{
public static void main(String[] args) {
CounterThread thread = new CounterThread();
thread.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
thread.stopped = true;
System.out.println("exit");
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Thread