在早期,我们使用stop方法终止线程
但此方法已经过时,因为强制杀死线程,会造成线程正在使用的资源(IO资源等)无法释放
现在我们采用interrupt(),相当于给线程打一个标记
我们看一下具体用法:
public class Demo {
public static void main(String[] args) throws InterruptedException {
//线程的中断
Thread t1 = new Thread(new MyRunnable());
t1.start();
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
Thread.sleep(100);
}
t1.interrupt();
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
//e.printStackTrace();
System.out.println("发现了中断标记,此线程自杀");
return;
}
}
}
}
控制台内容为:
main:0
Thread-0:0
Thread-0:1
main:1
Thread-0:2
main:2
main:3
Thread-0:3
main:4
Thread-0:4
Thread-0:5
发现了中断标记,此线程自杀
Process finished with exit code 0