目标
一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止。
Thread.interrupt 的作用其实也不是中断线程,而是「通知线程应该中断」
代码
package com.zoterap.javabasic.current;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import static java.lang.String.format;
import static java.util.concurrent.TimeUnit.SECONDS;
public class ThreadInterruptDemo {
public static String getCurrentTime() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS"));
}
public static void main(String[] args) {
Thread t = new Thread(() -> {
for (int i = 0; i < 10; i++) {
System.out.println(format("current i[%d], dateTime[%s]", i, getCurrentTime()));
try {
SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.println("EXCEPTION:" + e.getMessage());
Thread.currentThread().interrupt();
}
}
});
/**
* 开启线程
*/
t.start();
/**
* 主线程休眠5秒
*/
try {
SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 打印线程,尝试中断
*/
t.interrupt();
}
}
结果
current i[0], dateTime[2019-02-13 21:24:33 988]
current i[1], dateTime[2019-02-13 21:24:35 011]
current i[2], dateTime[2019-02-13 21:24:36 015]
current i[3], dateTime[2019-02-13 21:24:37 020]
current i[4], dateTime[2019-02-13 21:24:38 022]
EXCEPTION:sleep interrupted
current i[5], dateTime[2019-02-13 21:24:38 963]
EXCEPTION:sleep interrupted
current i[6], dateTime[2019-02-13 21:24:38 964]
EXCEPTION:sleep interrupted
current i[7], dateTime[2019-02-13 21:24:38 964]
EXCEPTION:sleep interrupted
current i[8], dateTime[2019-02-13 21:24:38 964]
EXCEPTION:sleep interrupted
current i[9], dateTime[2019-02-13 21:24:38 965]
EXCEPTION:sleep interrupted