Java8-Executors-No.01


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

public class Executors1 {

    public static void main(String[] args) {
        test1(3);
//        test1(7);
    }

    private static void test1(long seconds) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(seconds);
                String name = Thread.currentThread().getName();
                System.out.println("task finished: " + name);
            }
            catch (InterruptedException e) {
                System.err.println("task interrupted");
            }
        });
        stop(executor);
    }

    static void stop(ExecutorService executor) {
        try {
            System.out.println("attempt to shutdown executor");
            executor.shutdown();
            executor.awaitTermination(5, TimeUnit.SECONDS);
        }
        catch (InterruptedException e) {
            System.err.println("termination interrupted");
        }
        finally {
            if (!executor.isTerminated()) {
                System.err.println("killing non-finished tasks");
            }
            executor.shutdownNow();
            System.out.println("shutdown finished");
        }
    }
}

转载于:https://www.cnblogs.com/bilaisheng/p/10210907.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
An ExecutorService is an Executor that provides additional methods for managing termination and tracking the progress of asynchronous tasks. It extends the base Executor interface and adds functionalities such as task submission, task cancellation, and waiting for task completion. An ExecutorService can be shut down, which means it will stop accepting new tasks and initiate the process of terminating existing tasks. There are two methods provided for shutting down an ExecutorService: 1. `shutdown()`: This method allows previously submitted tasks to complete execution before terminating the ExecutorService. It will not interrupt already running tasks, but it will prevent new tasks from being accepted. 2. `shutdownNow()`: This method attempts to stop all actively executing tasks and prevents waiting tasks from starting. It interrupts the running tasks and may forcibly terminate them. Once an ExecutorService is shut down, it reaches a terminated state where no tasks are actively executing, no tasks are awaiting execution, and no new tasks can be submitted. It is recommended to shut down an unused ExecutorService to release its resources. The `submit()` method is an extended version of the base `execute(Runnable)` method in the Executor interface. It submits a task for execution and returns a Future object that can be used to track the progress of the task, cancel its execution, or wait for its completion. The `invokeAny()` and `invokeAll()` methods are higher-level methods that execute a collection of tasks and wait for their completion. `invokeAny()` waits for at least one task to complete and returns the result of the first completed task. `invokeAll()` waits for all tasks to complete and returns a list of Future objects representing the results of all tasks. The Executors class provides factory methods for creating different types of ExecutorService instances. For example, `Executors.newFixedThreadPool()` creates a thread pool with a fixed number of threads. Here's an example usage of an ExecutorService with a fixed thread pool: ```java ExecutorService executor = Executors.newFixedThreadPool(5); // Submit tasks for execution executor.submit(new Task1()); executor.submit(new Task2()); // Shut down the executor when no longer needed executor.shutdown(); ``` In this example, a fixed thread pool with 5 threads is created using the `newFixedThreadPool()` method. Two tasks, `Task1` and `Task2`, are submitted for execution using the `submit()` method. Finally, the executor is shut down using the `shutdown()` method.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值