當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Executors newSingleThreadExecutor()用法及代碼示例


Executors 類的 newSingleThreadExecutor() 方法創建一個 Executor,該 Executor 使用單個工作線程在無界隊列上運行。 (但請注意,如果該單個線程在關閉前的執行過程中因失敗而終止,則在需要執行後續任務時將替換為一個新線程。)。

用法

public static ExecutorService newSingleThreadExecutor()
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory)

參數

threadFactory - 創建新線程時使用的工廠

返回

新創建的 single-threaded Executor

拋出

NullPointerException

例子1

//import statement
 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorsnewSingleThreadExecutorExample1  {
    public static void main(String[] args) {
        System.out.println("current thread:" + Thread.currentThread().getName());

        System.out.println(" Executor Service...");
        ExecutorService ex  = Executors.newSingleThreadExecutor();

        System.out.println("Runnable...");
        Runnable runnable = () -> {
            System.out.println("::" + Thread.currentThread().getName());
        };

        System.out.println("Submit the task ");
        ex.submit(runnable);
    }
}

輸出:

current thread:main
 Executor Service...
Runnable...
Submit the task 
::pool-1-thread-1

例子1

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ExecutorsnewSingleThreadExecutorExample2   {

   public static void main(final String[] arguments) throws InterruptedException {
      ExecutorService ex = Executors.newSingleThreadExecutor();

      try {
         ex.submit(new myThread5());
         System.out.println("Shutingdown executor");
         ex.shutdown();
         ex.awaitTermination(10, TimeUnit.SECONDS);
      } catch (InterruptedException e) {
         System.err.println(e);
      } finally {

         if (!ex.isTerminated()) {
            System.err.println("cancel  tasks");
         }
         ex.shutdownNow();
         System.out.println(" finished");
      }
   }

   static class myThread5 implements Runnable {
      
      public void run() {

         try {
            Long duration = (long) (Math.random() * 90);
            System.out.println("Running Task!");
            TimeUnit.SECONDS.sleep(duration);
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}

輸出:

Shutingdown executor
Running Task!




相關用法


注:本文由純淨天空篩選整理自 Java Executors newSingleThreadExecutor() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。