<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # Java 線程池示例 > 原文: [https://javatutorial.net/java-thread-pool-example](https://javatutorial.net/java-thread-pool-example) 活動線程消耗系統資源,這可能導致 [JVM](https://javatutorial.net/jvm-explained) 創建太多線程,這意味著系統將很快用盡內存。 ![java-featured-image](https://img.kancloud.cn/05/3e/053ee0bb59842d92359246c98f815e0c_780x330.jpg) 這就是 Java 中的線程池有助于解決的問題。 ## 線程池如何工作? 線程池將先前創建的線程重用于當前任務。 這就解決了需要太多線程的問題,因此內存不足不是一個選擇。 您甚至可以將線程池??視為回收系統。 它不僅消除了用盡內存的選項,而且還使應用程序非常快速地響應,因為當請求到達時已經存在一個線程。 ![Thread Pool Java](https://img.kancloud.cn/56/2f/562f33b3c65344719d9b7b2d3a145c64_715x711.jpg) 上圖的工作流不僅可以控制應用程序正在創建的線程數,還可以控制計劃任務的執行并將傳入的任務保持在隊列中。 ## `Executor`,`Runnable`和`ExecutorService` Java 提供了`Executor`框架,這意味著您只需要實現`Runnable`對象并將其發送給執行器即可執行。 要使用線程池,首先我們需要創建一個`ExecutorService`對象并將任務傳遞給它。`ThreadPoolExecutor`類設置核心和最大池大小。 然后,可運行對象將順序執行。 ## 不同的`Executor`線程池方法 ```java newFixedThreadPool(int size) - creates a fixed size thread pool newCachedThreadPool() - creates a thread pool that creates new threads if needed but will also use previous threads if they are available newSingleThreadExecutor() - creates a single thread ``` `ExecutorService`接口包含許多方法,這些方法用于控制任務的進度并管理服務的終止。 您可以使用`Future`實例控制任務的執行。 有關如何使用`Future`的示例: ```java ExecutorService execService = Executors.newFixedThreadPool(6); Future<String> future = execService.submit(() -> "Example"); String result = future.get(); ``` `ThreadPoolExecutor`使您可以實現具有許多參數的可擴展線程池,這些參數包括`corePoolSize`,`maximumPoolSize`,`keepAliveTime`,`unit`,`workQueue`,`handler`,`threadFactor`。 但是,`corePoolSize`,`maximumPoolSize`和`keepAliveTime`是主要變量,因為它們在每個構造函數中都使用。 `corePoolSize`是要保留在池中的線??程數,即使它們處于空閑狀態,除非設置了`allowCoreThreadTimeOut`。 `maximumPoolSize`是池中允許的最大線程數。 `keepAliveTime`是當線程數大于內核數時,這是多余的空閑線程將在終止之前等待新任務的最長時間。 有關其他參數的更多信息,請訪問[原始 Oracle 文檔](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html)。 ## 線程池實現示例 工作流程步驟: 1. 創建要執行的任務 2. 使用執行程序創建執行程序池 3. 將任務傳遞給執行程序池 4. 關閉執行程序池 `Task.java` ```java import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; // (Step 1) public class Task implements Runnable { private String name; public Task(String name) { this.name = name; } public void run() { try { for (int i = 0; i < 5; i++) { if (i == 1) { Date date = new Date(); SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); System.out.println("Time initialization for task " + this.name + " is " + ft.format(date)); } else { Date date = new Date(); SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss"); System.out.println("Execution time for task " + this.name + " is " + ft.format(date)); } Thread.sleep(1000); } } catch(InterruptedException error) { error.printStackTrace(); } System.out.println(this.name + " completed"); } } ``` `Main.java` ```java import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { Runnable task1 = new Task("task 1"); Runnable task2 = new Task("task 2"); Runnable task3 = new Task("task 3"); Runnable task4 = new Task("task 4"); Runnable task5 = new Task("task 5"); // (Step 2) ExecutorService pool = Executors.newFixedThreadPool(3); // (Step 3) pool.execute(task1); pool.execute(task2); pool.execute(task3); pool.execute(task4); pool.execute(task5); // (Step 4) pool.shutdown(); } } ``` **輸出**: ```java Time initialization for task task 2 is 10:18:40 Time initialization for task task 1 is 10:18:40 Time initialization for task task 3 is 10:18:40 Execution time for task task 3 is 10:18:41 Execution time for task task 1 is 10:18:41 Execution time for task task 2 is 10:18:41 Execution time for task task 2 is 10:18:42 Execution time for task task 3 is 10:18:42 Execution time for task task 1 is 10:18:42 Execution time for task task 1 is 10:18:43 Execution time for task task 3 is 10:18:43 Execution time for task task 2 is 10:18:43 Execution time for task task 3 is 10:18:44 Execution time for task task 1 is 10:18:44 Execution time for task task 2 is 10:18:44 task 2 completed task 1 completed task 3 completed Time initialization for task task 4 is 10:18:45 Time initialization for task task 5 is 10:18:45 Execution time for task task 4 is 10:18:46 Execution time for task task 5 is 10:18:46 Execution time for task task 4 is 10:18:47 Execution time for task task 5 is 10:18:47 Execution time for task task 5 is 10:18:48 Execution time for task task 4 is 10:18:48 Execution time for task task 4 is 10:18:49 Execution time for task task 5 is 10:18:49 task 4 completed task 5 completed ``` **上面的代碼實現的細分**: `Task.java`表示任務類。 每個任務都有一個名稱實例變量,并且每個任務都使用構造函數實例化。 此類有 1 個方法,稱為`run`。 在`run`方法的主體內,有一個`for`循環,該循環根據存在的任務數進行迭代。 在我們的例子中,有 5 個任務,這意味著它將運行 5 次。 第一次迭代,顯示當前任務初始化的時間。 其他迭代,打印執行時間。 打印完成后,有一個`Thread.sleep()`方法調用,該方法用于以 1 秒的延遲顯示每個迭代消息。 **注意**,像這樣調用的方法名稱`run`非常重要,因為它是來自`Task`類正在實現的`Runnable`的抽象方法。 僅在池中的某個胎面變得空閑時才執行任務 4 和 5。 在此之前,額外的任務將放置在隊列中。 執行完所有任務后,請關閉線程池。 ## 線程池何時有用 組織服務器應用程序時。 如本文開頭所述,在組織服務器應用程序時非常有用,因為使用線程池非常有效,就像有許多任務一樣,它會自動將它們放入隊列中。 不僅如此,它還可以防止內存不足,或者至少可以顯著減慢這樣做的速度。 使用`ExecutorService`使其更易于實現。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看