interrupt() 方法
其作用是中断此线程(此线程不一定是当前线程,而是指调用该方法的Thread实例所代表的线程),但实际上只是给线程设置一个中断标志,线程仍会继续运行。
实例: 先输出10次线程名,然后等待20秒,在主方法调用interrupt()方法。
class ThreadTest extends Thread {
@Override
public void run() {
while (true) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
try {
Thread.sleep(20000);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " 中断");
}
}
}
}
主方法
public static void main(String[] args) {
Thre