Executors执行器newSingleThreadExecutor方法示例

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

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

Executors.newSingleThreadExecutor() 方法

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

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

  1. ExecutorService executorService = Executors.newSingleThreadExecutor();

Executors.newSingleThreadExecutor() 方法实例

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

  1. import java.util.concurrent.ExecutionException;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.TimeUnit;
  5. /*
  6. * Instantiates a thread pool with a single thread
  7. * All tasks are executed sequentially by the same thread
  8. */
  9. public class SingleThreadPoolExample {
  10. public static void main(String[] args) throws InterruptedException, ExecutionException {
  11. System.out.println("Thread main started");
  12. Runnable task1 = () -> {
  13. System.out.println("Executing Task1 inside : " + Thread.currentThread().getName());
  14. try {
  15. TimeUnit.SECONDS.sleep(2);
  16. } catch (InterruptedException ex) {
  17. throw new IllegalStateException(ex);
  18. }
  19. };
  20. Runnable task2 = () -> {
  21. System.out.println("Executing Task2 inside : " + Thread.currentThread().getName());
  22. try {
  23. TimeUnit.SECONDS.sleep(4);
  24. } catch (InterruptedException ex) {
  25. throw new IllegalStateException(ex);
  26. }
  27. };
  28. Runnable task3 = () -> {
  29. System.out.println("Executing Task3 inside : " + Thread.currentThread().getName());
  30. try {
  31. TimeUnit.SECONDS.sleep(3);
  32. } catch (InterruptedException ex) {
  33. throw new IllegalStateException(ex);
  34. }
  35. };
  36. final ExecutorService executorService = Executors.newSingleThreadExecutor();
  37. System.out.println("Submitting the tasks for execution...");
  38. executorService.submit(task1);
  39. executorService.submit(task2);
  40. executorService.submit(task3);
  41. executorService.shutdown();
  42. System.out.println("Thread main finished");
  43. }
  44. }

输出:

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

相关文章