1、Thread中的interrupt()对正在执行的线程有用吗?也就是假如在main中有下面代码段:
Thread t = new Thread(new MyRunnable());
t.start();//t的run方法只做一件事,不断的打印而已
t.interrupt();//这句对t起什么作用了吗?是不是将t的interrupted status设成true而已,根本没别的影响?2、能举例说明一下:一个线程t由于调用sleep、wait、join阻塞的时候,如果这时调用t.interrupt()会抛出InterruptedException,特别是wait和join的时候的情况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呢?4、是不是只能interrupt(好像interrupt不一定中断一个线程)自己,其实就是下面这句是不是对的:
The current thread can only interrupt itself(稍微修改了文档上的一句话)
Thread t = new Thread(new MyRunnable());
t.start();//t的run方法只做一件事,不断的打印而已
t.interrupt();//这句对t起什么作用了吗?是不是将t的interrupted status设成true而已,根本没别的影响?2、能举例说明一下:一个线程t由于调用sleep、wait、join阻塞的时候,如果这时调用t.interrupt()会抛出InterruptedException,特别是wait和join的时候的情况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呢?4、是不是只能interrupt(好像interrupt不一定中断一个线程)自己,其实就是下面这句是不是对的:
The current thread can only interrupt itself(稍微修改了文档上的一句话)
这个应该可以解决你的问题
这个对于一个线程,仅仅是个标记,不会有其他的影响,但是当该线程正在
wait,sleep,join的时候会抛出InterruptedException。
另外,对于一个处于不活动状态的线程,你调用interrupt()没有任何影响。
当然一个线程对象可以通过调用interrupt设置中断标志,
在其他的线程也可以通过对该线程的引用中断被引用的线程。
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 void run() {
while(true){
if(this.isInterrupted()){
System.out.println("exit*****************");
return;
}
System.out.println(name); }
}
}
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();
}
}
}
线程是自己才能停止自己的运行.别人的interrupt()只是一种请求而已.
t.interrupt()不就是线程对象t将它start的线程的interrupted status设成true吗
我认为无论如何,一个线程只能interrupt自己
可能还有什么情况我没考虑到吧
请大哥继续讲解一下