I am trying to spawn a new thread within another thread. I am not able to stop the thread no matter what. Is there any way I can exit cleanly after performing operations.
package p.Threads;
public class Thread2 {
private volatile boolean flag = false;
public Thread2(){
Thread t2 = new Thread(){
public void run(){
System.out.println("t2 started :::::::::::::: ");
Thread2 t3 = new Thread2();
try {
t3.start2ndThread();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
};
t2.start();
t2.interrupt();
}
public void start2ndThread() throws InterruptedException{
Runnable r3 = new Runnable() {
@Override
public void run() {
System.out.println("Thread t3 started >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Thread t3 = new Thread(r3);
t3.start();
t3.join(2000);
terminate();
}
public void terminate(){
flag = true;
}
public static void main(String[] args) {
Thread2 thread2 = new Thread2();
}
}