Whenever we want to stop a thread from running further, we may do so by calling stop() method, like:
aThread.stop();
This statement causes the thread to move to the dead state. A thread will also move to the dead state automatically when it reaches the end of its method. The stop() method may be used when the premature death of a thread is desired.
sleep() //blocked for a specified time
suspend() // blocked until further orders
wait() //blocked until certain condition orders
//Program to demonstrate stop() and sleep().
class ThreadA extends Thread{
public void run() {
for(int i=1;i<=5;i++) {
System.out.println("Running thread "+i+" From Class A");
if(i==3) stop();
}
System.out.println("Exit from Class A");
}}
class ThreadB extends Thread{
public void run() {
for(int j=1;j<=5;j++) {
System.out.println("Running thread "+j+" From Class B");
if(j==2)
try {
sleep(1000); //in milliseconds
//sleep must be surrounded with try/catch
} catch (Exception e) { System.out.println(e);
}
}
System.out.println("Exit from Class B");
}
}
class ThreadC extends Thread{
public void run() {
for(int k=1;k<=5;k++) {
System.out.println("Running thread "+k+" From Class C");
}
System.out.println("Exit from Class C");
}
}
public class ThreadExample {
public static void main(String[] args) {
new ThreadA().start(); new ThreadB().start(); new ThreadC().start();
}
}
Output