多线程——interrupt方法

时间:2023-03-09 17:45:40
多线程——interrupt方法

测试interrupt()方法:

package day_12_01_Thread;

import java.util.Date;

/**
* 测试interrupt()方法:结束线程,但是线程还是活着的
*
* @author Administrator
*
*/
public class MyThreadSleep {
public static void main(String[] args) {
TestThreadSleep testThreadSleep = new TestThreadSleep();
testThreadSleep.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
testThreadSleep.interrupt();
System.out.println(testThreadSleep.isAlive());
}
} class TestThreadSleep extends Thread {
public void run() {
while (true) {
System.out.println("当前时间:" + new Date());
try {
sleep(1000);
} catch (InterruptedException e) {
return;
}
}
}
}
结果:
当前时间:Mon May 14 13:05:56 CST 2018
当前时间:Mon May 14 13:05:59 CST 2018
当前时间:Mon May 14 13:06:00 CST 2018
当前时间:Mon May 14 13:06:01 CST 2018
当前时间:Mon May 14 13:06:02 CST 2018
当前时间:Mon May 14 13:06:03 CST 2018
当前时间:Mon May 14 13:06:04 CST 2018
当前时间:Mon May 14 13:06:05 CST 2018
当前时间:Mon May 14 13:06:06 CST 2018
true