一:直接看demo
public class MyThread extends Thread{
@Override
public void run() {
boolean flag = true;
while (flag) {
System.out.println("-------"+new Date()+"----");
try {
sleep(1000);
} catch (InterruptedException e) {
flag = false;
//run方法一结束,线程终止
}
}
}
}
public class TestInterrupt {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
try {
//Thread方法在哪个线程调用,就表示哪个线程。这里是在mian主线程
Thread.sleep(10000);
} catch (InterruptedException e) {
}
//打断thread线程
thread.interrupt();
}
}
输出结果:
-------Tue Feb 03 19:57:02 CST 2015----
-------Tue Feb 03 19:57:03 CST 2015----
-------Tue Feb 03 19:57:04 CST 2015----
-------Tue Feb 03 19:57:05 CST 2015----
-------Tue Feb 03 19:57:06 CST 2015----
-------Tue Feb 03 19:57:07 CST 2015----
-------Tue Feb 03 19:57:08 CST 2015----
-------Tue Feb 03 19:57:09 CST 2015----
-------Tue Feb 03 19:57:10 CST 2015----
-------Tue Feb 03 19:57:11 CST 2015----
-------Tue Feb 03 19:57:03 CST 2015----
-------Tue Feb 03 19:57:04 CST 2015----
-------Tue Feb 03 19:57:05 CST 2015----
-------Tue Feb 03 19:57:06 CST 2015----
-------Tue Feb 03 19:57:07 CST 2015----
-------Tue Feb 03 19:57:08 CST 2015----
-------Tue Feb 03 19:57:09 CST 2015----
-------Tue Feb 03 19:57:10 CST 2015----
-------Tue Feb 03 19:57:11 CST 2015----
可以看出,10秒后,线程终止 ,thread.interrupt();表示打断线程。
二:知识点
(1)Thread.sleep(10000);Thread方法在哪个线程调用,就表示哪个线程。这里是在mian主线程
(2)sleep方法的底层实现:throws InterruptedException
public static native void sleep(long millis) throws InterruptedException;
所以在调用sleep方法时,必须对其异常进行捕获。
(3)interrupt()打断终止线程,很粗暴!
(4)sleep()休眠一段时间,并不是终止!