Executors执行器newSingleThreadExecutor方法示例

x33g5p2x  于2022-10-06 转载在 其他  
字(2.0k)|赞(0)|评价(0)|浏览(730)

在本教程中,我们将学习Executor的newSingleThreadExecutorfactory方法。

Executors.newSingleThreadExecutor() 方法

这个方法创建了一个Executorthat,它使用一个单一的工作线程,从一个无界队列中运行。(但是请注意,如果这个单线程在关机前的执行过程中由于故障而终止,如果需要执行后续的任务,一个新的线程将取代它的位置)。任务被保证按顺序执行,并且在任何时候都不会有多于一个任务处于活动状态。与其他同等的e1d2d1不同,返回的执行器被保证不能被重新配置以使用额外的线程。

请注意,Executors.newSingleThreadExecutor()方法返回新创建的单线程执行器。
语法。

ExecutorService executorService = Executors.newSingleThreadExecutor();

Executors.newSingleThreadExecutor() 方法实例

在这个例子中,我们用一个单线程实例化了一个线程池。所有的任务都由同一个线程按顺序执行。

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

/*
* Instantiates a thread pool with a single thread
* All tasks are executed sequentially by the same thread
*/

public class SingleThreadPoolExample {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        System.out.println("Thread main started");

        Runnable task1 = () -> {
             System.out.println("Executing Task1 inside : " + Thread.currentThread().getName());
             try {
                 TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException ex) {
                 throw new IllegalStateException(ex);
            }
        };

        Runnable task2 = () -> {
             System.out.println("Executing Task2 inside : " + Thread.currentThread().getName());
             try {
                  TimeUnit.SECONDS.sleep(4);
             } catch (InterruptedException ex) {
                  throw new IllegalStateException(ex);
             }
        };

        Runnable task3 = () -> {
             System.out.println("Executing Task3 inside : " + Thread.currentThread().getName());
            try {
                 TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException ex) {
                 throw new IllegalStateException(ex);
            }
       };

       final ExecutorService executorService = Executors.newSingleThreadExecutor();
       System.out.println("Submitting the tasks for execution...");
       executorService.submit(task1);
       executorService.submit(task2);
       executorService.submit(task3);

       executorService.shutdown();

       System.out.println("Thread main finished");
    }
}

输出:

Thread main started
Submitting the tasks for execution...
Executing Task1 inside : pool-1-thread-1
Thread main finished
Executing Task2 inside : pool-1-thread-1
Executing Task3 inside : pool-1-thread-1

相关文章