一个变量里,例如t,然后通过t去停止这个线程。停止线程的方法一般有stop,destroy,interrupt等,但是stop,destroy都已经被废弃了,因为可能造成死锁,所以通常等做法是使用interrupt。使用interrupt其实类似于信号,就好比你在Linux进程中把SIGTERM信号忽略了,那就没法通过kill杀死进程了,interrupt也是如此。 下面等线程只会报一个异常,中断信号被忽略。
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
System.out.println("wake up");
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
t.interrupt();//并不能停止线程
}
这种阻塞的线程,一般调用的函数都会强制检查并抛出interruption异常,类似的还有wait(),阻塞队列的take等,为了程序能正常关闭,InterruptedException最好不好忽略。
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
System.out.println("wake up");
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("stop...");
break;
}
}
}
});
t.start();
t.interrupt();
}
如果run方法里没有抛出InterruptedException怎么办?例如下面这个
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (true) {
i++;
}
}
});
t.start();
t.interrupt();
}
这种情况就需要run方法里不断检查是否被中断了,否则永远停不下来。
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (true) {
i++;
if(Thread.interrupted()) {
System.out.println("stop..");
break;
}
}
}
});
&n