1、Thread中的interrupt()对正在执行的线程有用吗?也就是假如在main中有下面代码段:
Thread t = new Thread(new MyRunnable());
t.start();//t的run方法只做一件事,不断的打印而已
t.interrupt();//这句对t起什么作用了吗?是不是将t的interrupted status设成true而已,根本没别的影响?
第一问你的理解是正确的,
这个对于一个线程,仅仅是个标记,不会有其他的影响,但是当该线程正在
wait,sleep,join的时候会抛出InterruptedException。
另外,对于一个处于不活动状态的线程,你调用interrupt()没有任何影响。
2、能举例说明一下:一个线程t由于调用sleep、wait、join阻塞的时候,如果这时调用t.interrupt()会抛出InterruptedException,特别是wait和join的时候的情况
public class Test extends Thread {
private String name;
public Test(String name) {
this.name = name;
}
public static void main(String[]args) throws Exception{
Thread t1=new Test("myThread");
t1.start();
sleep(1000);
t1.interrupt();
}
public synchronized void run(){
try{
wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
3、Core Java有这样一句话:
However, if a thread is blocked, it cannot check the interrupted status. This is
where the InterruptedException comes in.?
为什么说InterruptedException come in here呢?
第三问:
当然一个线程对象可以通过调用interrupt设置中断标志,
在其他的线程也可以通过对该线程的引用中断被引用的线程。
4、是不是只能interrupt(好像interrupt不一定中断一个线程)自己,其实就是下面这句是不是对的:
The current thread can only interrupt itself(稍微修改了文档上的一句话)
要想打断他,当然要有他的实例了,当然也就只能打断这个了。