import java.util.*;
public class TestInterrupt {
public static void main (String []args) {
MyRunnable1 myRunnable = new MyRunnable1();
Thread myThread = new Thread();
myThread.start();
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
myThread.interrupt();
}
}
class MyRunnable1 implements Runnable{
public void run () {
while(true) {
try {
Thread.sleep(500);
System.out.println("---" + new Date() + "---");
} catch (InterruptedException e) {
return;
}
}
}
}
该程序目的是每过0.5秒在命令行窗口输出一行字符串,30秒后结束,编译通过了,但运行时命令行窗口没有任何的输出,是为什么?
Thread myThread = new Thread(myRunnable );//将目标对象传进来
myThread.interrupt(); 中断线程,这个线程收到中断信号后, 会抛出InterruptedException, 同时会把中断状态置回为true.
try {
Thread.sleep(500);
System.out.println("---" + new Date() + "---");
} catch (InterruptedException e) {
return;
}//捕捉到异常直接跳出循环;
至于没修改前窗口没有任何的输出,是因为两条线程的运行顺序不能确定,一直试下去会出线一条时间记录的现象。