I have developed a code that will start two threads upon executing
public class MyThread1 extends Thread //extend thread class
{
// public synchronized void run()
//synchronized (this)
public void run()
{//synchronized(this)
//{
for(int i=0;i<20;++i) {
try{
Thread.sleep(500);
System.out.print(i +"\n"+ "..");
}catch(Exception e)
{e.printStackTrace();}
//}
}
}
public static void main(String... a)
{
MyThread1 t = new MyThread1();
Thread x = new Thread(t);
Thread y = new Thread(t);
x.start();
y.start();
}
Now it starts both the threads but what if I want to stop a particular thread, lets say I want to stop Thread Y then How I will do it please advise since stopping a thread means that it’s run method is completed but I want to stop it forcefully how I will do this, please advise
You should
interrupt()the thread. Blocking calls (likesleep()) will throw an InterruptedException when the thread is interrupted. If you want to stop as fast as possible while in a tight loop, regularly check is the current thread has been interrupted using theisInterrupted()method.More information about this in the Java concurrency tutorial.