public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Runnable r=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try{
Thread.sleep(5000);
}catch(InterruptedException e){
System.out.println("interrupted");
}
System.out.println("ran");
}
};
Thread t=new Thread(r);
t.start();
System.out.println("started");
t.sleep(2000);
System.out.println("interrupting");
t.interrupt();
System.out.println("ended");
}
}
为什么会输出
started
interrupting
interrupted
ran
ended
而t.sleep()中的数字大于5000时则输出
started
ran
interrupting
ended
首先,sleep是Thread类的静态方法,它只会让当前线程休眠,在main函数中的t. sleep本质上是让main线程休眠,而不是让线程t休眠,你的Runnable中的休眠方法调用才是正确的。其次,分析下休眠时间,main线程休眠超过5秒后才中断线程t,而此时线程t已经运行结束了,所以这个t. interrupt操作已经失效了。不超过5秒时,线程t仍处于休眠阶段而响应中断进入异常分支,所以打印了中断信息。
在阻塞操作时如Thread.sleep()时被中断会抛出InterruptedException(注意,进行不能中断的IO操作而阻塞和要获得对象的锁调用对象的synchronized方法而阻塞时不会抛出InterruptedException)
线程:
线程,有时被称为轻量级进程(Lightweight Process,LWP),是程序执行流的最小单元。一个标准的线程由线程ID,当前指令指针(PC),寄存器集合和堆栈组成。另外,线程是进程中的一个实体,是被系统独立调度和分派的基本单位,线程自己不拥有系统资源,只拥有一点儿在运行中必不可少的资源,但它可与同属一个进程的其它线程共享进程所拥有的全部资源。Java中的线程有......
答案就在这里:Java线程基础知识
----------------------你好,人类,我是来自CSDN星球的问答机器人小C,以上是依据我对问题的理解给出的答案,如果解决了你的问题,望采纳。