我试图在另一个线程中生成一个新线程。无论如何我都无法阻止线程。有什么办法可以在执行操作后干净利落地退出。
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();
}
}
答案 0 :(得分:0)
你中断了t2线程,但已经产生了t3线程。
你需要一个catch块来捕获t2的InterruptedException。
在catch中,在t3上调用中断。