2017-10-12 66 views
0
public class TimeToDieThread extends Thread implements Runnable 
{ 
    private Runnable r; 
    private long lTimeLength;//time NanoTime 

    public TimeToDieThread(Runnable r, long lTimeLength) 
    { 
     super(); 
     this.r = r; 
     this.lTimeLength = lTimeLength; 
    } 
    public void start() { 
     Thread t = new Thread(new Runnable() { 
      @Override 
      public void run() { 
       boolean bran = false; 
       while ((!Thread.currentThread().isInterrupted()) && (bran == false)) { 
        r.run(); 
        bran = true; 
       } 
      } 
     }); 
     t.start(); 
     // Sleep a for entire length, and then interrupt 
     try 
     { 
      Thread.sleep(lTimeLength); 
     } catch (InterruptedException e) 
     { 
      System.out.println("Interrupted, wop wop waa"); 
     } 
     t.interrupt(); 
    } 
} 
+1

'r.run()'不会被这种方式中断,否。在运行while循环之前't.run()'可能会被打断(它只会循环一次,错字?)。 –

回答

2

这是很少需要直接使用Thread(这绝对不是必要延长Thread和实施Runnable,因为Thread已经实现Runnable)。

使用ExecutorService,提交Runnable即可,并在返回的Future上使用get(long, TimeUnit)方法等待它完成。

// Construct this somewhere. Note that you also need to shut it down somewhere. 
// This is just an example of how you might construct it; other executors are 
// available. 
ExecutorService executorService = Executors.newFixedThreadPool(nThreads); 

Future<?> future = executorService.submit(yourRunnable); 
future.get(timeout, timeoutUnit); // Exception handling omitted. 
// Cancel if it is still running. 
future.cancel(true); 
相关问题