interrupt并不能中断线程那它为啥叫interrupt啊
interrupt清楚阻塞状态并抛出异常,这和中断有啥关系?
interrupt清楚阻塞状态并抛出异常,这和中断有啥关系?
2017-01-24
是中断不是终断;
比如讲师在本节课中的一个例子:
package com.imooc.demo;
public class WrongWayStopThread extends Thread {
public static void main(String[] args) {
WrongWayStopThread thread = new WrongWayStopThread();
System.out.println("Starting thread");
thread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Tnterrupting thread");
thread.interrupt();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Stopping thread");
}
@Override
public void run() {
// 在线程之中,我们定义了一个无限循环的while()结构,在while()循环之中,我输出线程正在运行的信息
// 然后嵌套一个空的while()循环,减少屏幕输出,使得每秒只输出一行信息,它的作用大致相当于Thread.sleep(1000)
// 但是为什么不是Thread.sleep(1000)?
//
while (!this.isInterrupted()) {
System.out.println("Thread is running");
long time = System.currentTimeMillis();
while ((System.currentTimeMillis() - time) < 1000) {
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
}
}我们知道main也一个主线程,在执行到程序的入口,也就是main()方法的时候,程序就会产生一个线程,然后调用start()的时候会产生一个线程,这两个线程并行,调用Thread.sleep(3000),指的是让main这个主线程休眠3秒,我们的thread线程才抢占资源运行,随着main线程3秒后的恢复,thread线程就恢复了抢占资源的状态,然后main线程读取到了thread.interrupt(),也就是说thread线程进行了终止,那么isInterrupted()的返回值就是true,所以while()循环会停止,也就是说,thread线程结束了,然后经过Thread.sleep(),主线程就又停止了3秒,然后输出线程停止。
一家之言,敬请指正!
举报