I have created sample program of java Thread in which i am using stop() method to stop the thread using below program
public class App extends Thread
{
Thread th;
App(String threadName)
{
th = new Thread(threadName);
}
public synchronized void run() // Remove synchronized
{
for (int i = 0; i < 5; i++) {
System.out.println(th.getName()+" "+i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
public static void main( String[] args )
{
App thread_1 = new App("Thread-1");
thread_1.start();
thread_1.setPriority(MAX_PRIORITY); //Comment this
thread_1.stop();
App thread_2 = new App("Thread-2");
thread_2.start();
}
}
The output of the above program is :
Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 3
Thread-1 4
Thread-2 0
Thread-2 1
Thread-2 2
Thread-2 3
Thread-2 4
i.e. thread_1 is not stopped. When i am removing synchronized or priority in the code thread is stopped immediately and output will be
Thread-2 0
Thread-2 1
Thread-2 2
Thread-2 3
Thread-2 4
I am not able to understand why it is working like this.