我需要弄清楚为什么我在互联网上找到的关于如何从interrupt()方法中捕获Runnable#run()的每个例子都是这样的:
while (Thread.currentThread().isInterrupted()) {
//foo();
try {
Thread.sleep(1000);
} catch(InterruptingException e) {
Thread.currentThread().interrupt();
}
//foo();
}我现在已经足够理解线程了(我想是这样),我不明白为什么如果我们在run方法中,这不意味着我们可以用this代替Thread.currentThread()
发布于 2018-10-03 09:49:42
如果我们在run方法中,这不意味着Thread.currentThread() ==这个吗?
不是的。在run方法的Runnable中,this不等于current thread,它表示当前的Runnable实例。
Runnable只是一个普通的对象,可以用来构造一个新线程。当您使用Runnable构造Thread时:
Runnable runnable = ...
Thread thread = new Thread(runnable);线程和runnable仍然是不同的对象。
这个例子表明,它们是不同的东西:
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都将引用当前线程实例。
Thread thread = new Thread() {
@Override
public void run() {
// this == Thread.currentThread()
}
};还可以在任何方法中引用当前线程,无论是否可以在run方法中引用,例如,在main方法中:
public static void main (String[] args) throws Throwable {
Thread.currentThread().interrupt();
}发布于 2018-10-03 09:49:33
this to Runnable#run()指的是Runnable对象,而不是封闭的Thread对象。在这种情况下,Thread.currentThread() != this。
但是,如果像下面这样创建线程对象,则不鼓励这样做:
Thread thread = new Thread() {
@Override
public void run() {
System.out.println(Thread.currentThread() == this);
}
};然后是Thread.currentThread() == this。
发布于 2018-10-03 10:16:44
只有当this是线程时,才能用Thread.currentThread()替换this。这将需要扩展Thread,这很少是一个好主意。
无论如何,您不需要像这样使用Thread.currentThread()作为异常时,都会中断循环。
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();
}我倾向于假设中断的线程应该尽快停止,在这种情况下,在理想情况下不应该有任何工作被中断。
https://stackoverflow.com/questions/52624179
复制相似问题