2017-10-12 1 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()'はこのように中断されません。 't.run()'はwhileループを実行する前に中断することができます(とにかく一度だけループする、typo?)。 –

答えて

2

直接Threadを使用する必要はほとんどありません(と、それはThreadはすでにRunnableを実装しているため、Threadを拡張し、Runnableを実装するために絶対に必要はありません)。

ExecutorServiceを使用してRunnableを送信し、Futureget(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); 
関連する問題