书上(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"吗?新手,不解,求教!!

解决方案 »

  1.   

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

  2.   

    生产者消费者中经常有这种情况,一个执行线程跑死循环不停的从阻塞队列里边取出一个Runnable对象并执行它的run方法,另外一个线程则不停的往队列里边添加Runnable对象等待执行
      

  3.   


    书上的意思,应该是Tread里的run方法,原文有句话是这样的:The run method
    of such a thread has the following form:
    public void run()
    {
    try
    ......
    ......
    (就是上面我粘的代码)
      

  4.   

    Thread.currentThread()是获取当前的线程。如果当前线程本身就是个Thread,那么就能直接调用isInterrupted,相当于this.isInterrupted(),this是当前线程对象。但是有时候代码并不处于一个Thread对象里。那么this就不是thread对象了,所以此时必须Thread.currentThread()获取当前线程。
    LZ结帖率这么低,不结的话以后没人回答你的。
      

  5.   

    发现个怪事,我所有帖子(除了此贴)都结贴了,分都给了,竟然结贴率只有75%,不行你们上我空间看看。无语了。出bug了?
      

  6.   

    正如1L所说,The run method of such a thread has the following form:这里的thread并非指Thread类,而是指Thread对象,那么Thread对象可以通过new Thread(Runnable r)来生成,此时的run就并不是Thread类的,而是Runnable的