1. 使用退出标志,使线程正常退出,也就是使run方法完成后线程终止。
2. 使用stop方法强行终止线程(这个方法不推荐使用,因为stop和suspend、resume一样,也可能发生不可预料的结果)。
3. 使用interrupt方法中断线程。
其中第三种方法又分为:
(1)线程处于阻塞状态,如使用了sleep方法。
(2)使用while(!isInterrupted()){……}来判断线程是否被中断。
class MyThread extends Thread{
BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);
@Override
public void run() {
while(true){
try {
Integer take = queue.take();// 或者直接用sleep(1000)代替
} catch (InterruptedException e) {
//需要注意:在这里如果不跳出while循环,该线程仍将继续执行,并重置中断状态为false
e.printStackTrace();//当interrupt()被调用,且当前线程处于等待中,会抛出该异常
}
}
}
}