2016-05-31 50 views
0

全部, 我的英语很差,但我会尽力解释我的问题。Java并发实践L.90

的代码如下:

public class timedRun { 
    private static final ScheduledExecutorService cancelExec = newScheduledThreadPool(1); 

    public static void timedRun(final Runnable r, 
           long timeout, TimeUnit unit) 
      throws InterruptedException { 
     class RethrowableTask implements Runnable { 
      private volatile Throwable t; 

      public void run() { 
       try { 
        r.run(); 
       } catch (Throwable t) { 
        this.t = t; 
       } 
      } 

      void rethrow() { 
       if (t != null) 
        throw launderThrowable(t); 
      } 
     } 

     RethrowableTask task = new RethrowableTask(); 
     final Thread taskThread = new Thread(task); 
     taskThread.start(); 
     cancelExec.schedule(new Runnable() { 
      public void run() { 
       taskThread.interrupt(); 
      } 
     }, timeout, unit); 
     taskThread.join(unit.toMillis(timeout)); 
     task.rethrow(); 
    } 
} 

有书中声明:即使任务没有到回应响应,定时运行方法仍然可以返回到它的调用者。

我的问题是: 如果我把这个方法如下:

timedRun(new Runnable() { 
    @Override 
    public void run() { 
     while(true); 
    } 
}, /* doesn't matter */, /* doesn't matter */); 

如果R不中断请求响应,taskThread可能无法在此代码中断(对吗?) 所以这个程序可能没有实现定时运行的功能吗?

回答

0

Java中断协作:它依赖中断的事件来检查中断和适当地处理它。

如果您有类似while (true);的循环,它不会检查或响应中断。

你可以尝试这样的:

while (!Thread.currentThread().interrupted()); 

但是,这是一个“忙等待”:它会不断的次数远远多于它可能会改变检查中断标志。

这是一个很多只是为了更好地把线程无限期睡觉:

try { 
    Thread.sleep(Long.MAX_VALUE); 
} catch (InterruptedException e) { 
    // Maybe reset the interrupted flag, if appropriate. 
} 

因为直到线程是实际上中断,这并不做任何事情。