首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Thread.currentThread().interrupt()与this.interrupt()从Runnable#run()

Thread.currentThread().interrupt()与this.interrupt()从Runnable#run()
EN

Stack Overflow用户
提问于 2018-10-03 09:44:06
回答 3查看 539关注 0票数 1

我需要弄清楚为什么我在互联网上找到的关于如何从interrupt()方法中捕获Runnable#run()的每个例子都是这样的:

代码语言:javascript
复制
while (Thread.currentThread().isInterrupted()) {
    //foo();
    try {
        Thread.sleep(1000);
    } catch(InterruptingException e) {
        Thread.currentThread().interrupt();
    }
    //foo();
}

我现在已经足够理解线程了(我想是这样),我不明白为什么如果我们在run方法中,这不意味着我们可以用this代替Thread.currentThread()

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-10-03 09:49:42

如果我们在run方法中,这不意味着Thread.currentThread() ==这个吗?

不是的。在run方法的Runnable中,this不等于current thread,它表示当前的Runnable实例。

Runnable只是一个普通的对象,可以用来构造一个新线程。当您使用Runnable构造Thread时:

代码语言:javascript
复制
Runnable runnable = ...
Thread thread = new Thread(runnable);

线程和runnable仍然是不同的对象。

这个例子表明,它们是不同的东西:

代码语言:javascript
复制
public static void main (String[] args) throws Throwable {
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("inner runnable: " + this);   // inner runnable: com.Test$1@34ce8af7
        }
    };


    Thread thread = new Thread(runnable);

    System.out.println("thread:  " + thread); // thread:  Thread[Thread-0,5,main]
    System.out.println("runnable:  " + runnable); // runnable:  com.Test$1@34ce8af7

    thread.start();
    thread.join();
}

另外值得注意的是,java.lang.Thread还实现了Runnable接口,因此如果直接创建Thread并覆盖run方法,this关键字和Thread.currentThread都将引用当前线程实例。

代码语言:javascript
复制
Thread thread = new Thread() {
    @Override
    public void run() {
        // this == Thread.currentThread()
    }
};

还可以在任何方法中引用当前线程,无论是否可以在run方法中引用,例如,在main方法中:

代码语言:javascript
复制
public static void main (String[] args) throws Throwable {
    Thread.currentThread().interrupt();
}
票数 3
EN

Stack Overflow用户

发布于 2018-10-03 09:49:33

this to Runnable#run()指的是Runnable对象,而不是封闭的Thread对象。在这种情况下,Thread.currentThread() != this

但是,如果像下面这样创建线程对象,则不鼓励这样做:

代码语言:javascript
复制
Thread thread = new Thread() {
  @Override
  public void run() {
    System.out.println(Thread.currentThread() == this);
  }
};

然后是Thread.currentThread() == this

票数 3
EN

Stack Overflow用户

发布于 2018-10-03 10:16:44

只有当this是线程时,才能用Thread.currentThread()替换this。这将需要扩展Thread,这很少是一个好主意。

无论如何,您不需要像这样使用Thread.currentThread()作为异常时,都会中断循环。

代码语言:javascript
复制
try {
    while (true){
        try {
            //foo();
            Thread.sleep(1000);
        } finally {
            //foo();
        }
    }
} catch (InterruptingException e){
     // if the thread needs to continue after an interrupt.
     Thread.currentThread().interrupt();
}

我倾向于假设中断的线程应该尽快停止,在这种情况下,在理想情况下不应该有任何工作被中断。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52624179

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档