日期:2014-05-20  浏览次数:20791 次

关于Thread.currentThread()的问题
书上(Java核心技术,卷一,英文版,P728)举了个例子,说,要查看一个线程的“打断状态”是否被设置,首先调用Thread.currentThread(),再调用isInterrupted(),例如:while (!Thread.currentThread().isInterrupted() && more work to do)
{
do more work
}
一个线程可以对打断进行处理决定是否终止,但大多数的线程对于打断的处理应该是终止,这样的线程的run()方法应该如此:
public void run()
{
try
{
. . .
while (!Thread.currentThread().isInterrupted() && more work to do)
{
do more work
}
}
catch(InterruptedException e)
{
// thread was interrupted during sleep or wait
}
finally
{
cleanup, if required
}
// exiting the run method terminates the thread
}
我想问,为什么要调用Thread.currentThread()啊,直接调用isInterrupted()不行吗?因为
while (!Thread.currentThread().isInterrupted() && more work to do)这句不是在run方法里吗,获取了currentThread不也是"this"吗?

新手,不解,求教!!

------解决方案--------------------
未必,run方法有可能处于Runnable类中,而此类只是做为一种任务类存在,由其他线程直接调用run方法执行任务,此种情况下就无法调用isInterrupted()方法,再说Runnable接口中只有run方法一个,没有其他方法.

------解决方案--------------------
Thread.currentThread()是获取当前的线程。如果当前线程本身就是个Thread,那么就能直接调用isInterrupted,相当于this.isInterrupted(),this是当前线程对象。但是有时候代码并不处于一个Thread对象里。那么this就不是thread对象了,所以此时必须Thread.currentThread()获取当前线程。
LZ结帖率这么低,不结的话以后没人回答你的。
------解决方案--------------------
探讨
引用:
未必,run方法有可能处于Runnable类中,而此类只是做为一种任务类存在,由其他线程直接调用run方法执行任务,此种情况下就无法调用isInterrupted()方法,再说Runnable接口中只有run方法一个,没有其他方法.


书上的意思,应该是Tread里的run方法,原文有句话是这样的:The run method
of such……

------解决方案--------------------
探讨

引用:
引用:
未必,run方法有可能处于Runnable类中,而此类只是做为一种任务类存在,由其他线程直接调用run方法执行任务,此种情况下就无法调用isInterrupted()方法,再说Runnable接口中只有run方法一个,没有其他方法.


书上的意思,应该是Tread里的run方法,原文有句话是……