2015-07-10 62 views
1

我有Java Runnable,我正在執行run()方法。在該運行方法中有一些與服務器連接的連接,當它失敗時,我不再對線程執行感興趣,我想退出它。我做這樣的事情:如果我致電退貨會發生什麼;來自Runnable?

class MyRunnable implements Runnable { 
    @Override 
    public void run() { 
     // connect to server here 
     if (it failed) { 
      return; 
     } 

     // do something else 
    } 
} 

現在我提交此可運行爲Executors.cachedThreadPool()與我自己的線程工廠,基本上沒有什麼新東西。

我是安全的,從可運行這樣的回報?

我看着jvisualvm,看到線程池中有一個線程+有線程正在執行與服務器邏輯的連接,當我返回時,我看到這些連接線程停止,它們停留在列表中,但它們是白色的......

+0

是的,它只是一個方法調用。回來很好。 –

回答

2

你不提交線程執行者,您要提交的Runnable吧。在Runnable中調用返回不會導致執行它的線程終止。遺囑執行人是這麼寫的,它可以在的Runnable的形式運行多個任務,當一個Runnable完成執行(不管它是否早返回或其他)的線程將繼續,並且會從它的排隊等候的更多的工作提交的任務。

下面是在的ThreadPoolExecutor#runWorker方法的代碼。顯示task.run()的行是工作線程執行任務的地方,當您的任務返回時,工作人員的執行從此處開始。

final void runWorker(Worker w) { 
    Thread wt = Thread.currentThread(); 
    Runnable task = w.firstTask; 
    w.firstTask = null; 
    w.unlock(); // allow interrupts 
    boolean completedAbruptly = true; 
    try { 
     while (task != null || (task = getTask()) != null) { 
      w.lock(); 
      // If pool is stopping, ensure thread is interrupted; 
      // if not, ensure thread is not interrupted. This 
      // requires a recheck in second case to deal with 
      // shutdownNow race while clearing interrupt 
      if ((runStateAtLeast(ctl.get(), STOP) || 
       (Thread.interrupted() && 
        runStateAtLeast(ctl.get(), STOP))) && 
       !wt.isInterrupted()) 
       wt.interrupt(); 
      try { 
       beforeExecute(wt, task); 
       Throwable thrown = null; 
       try { 
        task.run(); 
       } catch (RuntimeException x) { 
        thrown = x; throw x; 
       } catch (Error x) { 
        thrown = x; throw x; 
       } catch (Throwable x) { 
        thrown = x; throw new Error(x); 
       } finally { 
        afterExecute(task, thrown); 
       } 
      } finally { 
       task = null; 
       w.completedTasks++; 
       w.unlock(); 
      } 
     } 
     completedAbruptly = false; 
    } finally { 
     processWorkerExit(w, completedAbruptly); 
    } 
} 
+0

是的,你是對的。我對此進行了測試,發現runnable可能會過早返回幾次,並且在JVM的整個生命週期中仍然有一個線程在jvisualvm中處於活動狀態,以便在閒置時重用線程。 – stewenson

3

這是完全正常使用returnvoid方法。它只是從該方法返回,在這種情況下將完成線程執行。

相關問題