Concurrent并发包详解
提前话:
进行myCat摸索时到处可见的并发包的原子性数据操作,与其摸瞎子过河,不如先把瞎子摸一遍!!!🤔 于是便有了下面这片的技术博客(关于concurrent概述)🤨
Overview of the java.util.concurrent(概述)
原文网址
Main Components(主要构成)
The java.util.concurrent contains way too many features to discuss in a single write-up. In this article, we will mainly focus on some of the most useful utilities from this package like:(在这片文章中如果一次撰写或讨论concurrent的功能、方式会太多,所以我们将大部分的精力集中于最常使用的实用程序)
Executor(执行者)
ExecutorService(执行器服务)
ScheduledExecutorService(执行器服务时间表)
Future
CountDownLatch
CyclicBarrier
Semaphore
ThreadFactory
BlockingQueue
DelayQueue
Locks
Phaser
You can also find many dedicated articles to individual classes here.
Executor
*Executor* is an interface that represents an object that executes provided tasks.
(Executor 是一个代表执行提供任务的一个接口对象)
It depends on the particular implementation (from where the invocation is initiated) if the task should be
它依赖于一个特定的实现(从启动调用的位置)如果这个任务需要运行在一个新线程或者当前线程
run on a new or current thread. Hence, using this interface, we can decouple the task execution flow from
因此,使用这个接口 我们可以将任务执行流与实际任务执行机制进行解耦(decouple)。
the actual task execution mechanism.
One point to note here is that Executor does not strictly require the task execution to be asynchronous.
这里需要注意的一点是,执行器并不严格要求任务执行是异步的。
In the simplest case, an executor can invoke the submitted task instantly in the invoking thread.
在这个简单的例子上, 执行者可以在调用线程中立即(instantly 即刻)调用提交的任务。
We need to create an invoker to create the executor instance:
我们需要生成一个调用者去生成一个执行者实例



看到上述的案例,想必你想问,那我直接print(“Hello Executor”)不行吗???(其实可以作为executor的生成案例) 我也正疑惑呢 so 得找个好案例
Executor
ExecutorService
ExecutorService is a complete solution for asynchronous processing.(执行器服务是异步进程的一个完整解决方案) It manages an in-memory queue and schedules submitted tasks based on thread availability.
它管理着内存中的队列(什么队列???🤔 🤨)并根据线程可用性安排已提交的任务。
To use ExecutorService, we need to create one Runnable class.

Now we can create the ExecutorService instance and assign this task. At the time of creation,
下面我们开始生成一个ExecutorService 实例并且分配一些任务,在生成的时候,我们需要指定线程池的大小
we need to specify the thread-pool size.
ExecutorService executor = Executors.newFixedThreadPool(10);If we want to create a single-threaded ExecutorService instance, we can use
如果我们想创建一个单线程的执行器服务实例,我们可以使用()去生成一个实例
*newSingleThreadExecutor(ThreadFactory threadFactory)* to create the instance.
Once the executor is created, we can use it to submit the task.
一旦这个执行者被生成,我们就可以使用它去提交任务
public void execute() {
executor.submit(new Task());
}We can also create the Runnable instance while submitting the task.
我们还可以在提交任务时创建Runnable实例。
executor.submit(() -> {
new Task();
});It also comes with two out-of-the-box execution termination methods.
它也有两种现成(out of the box)的执行终止方法
The first one is shutdown(); it waits until all the submitted tasks finish executing.
等待所有的提交任务执行完毕
The other method is shutdownNow() which immediately terminates all the pending/executing tasks.
该方法立即终止(terminates)所有待处理/正在执行的任务。
There is also another method awaitTermination(long timeout, TimeUnit unit)
which forcefully blocks until all tasks have completed execution after a shutdown event triggered
or execution-timeout occurred,
在触发关闭事件或发生执行超时后或者这个执行线程本身中断,它会强制阻塞直到所有任务都已完成执行,
or the execution thread itself is interrupted(中断),
try {
executor.awaitTermination( 20l, TimeUnit.NANOSECONDS );
} catch (InterruptedException e) {
e.printStackTrace();
}
ScheduledExecutorService
ScheduledExecutorService is a similar interface to ExecutorService, but it can perform tasks periodically.
xxx是类似于执行器服务的一个接口,但是它可定期执行任务,So you know that
*Executor and ExecutorService*‘s methods are scheduled on the spot without introducing any artificial delay.
XXX的方法是立即运行 没有引入任何人为的延迟
Zero or any negative value signifies that the request needs to be executed instantly.
零和任何负值都表示这个请求需要立即执行
We can use both Runnable and Callable interface to define the task.
public void execute() {
ScheduledExecutorService executorService
= Executors.newSingleThreadScheduledExecutor();
Future<String> future = executorService.schedule(() -> {
// ...
return "Hello world";
}, 1, TimeUnit.SECONDS);
ScheduledFuture<?> scheduledFuture = executorService.schedule(() -> {
// ...
}, 1, TimeUnit.SECONDS);
executorService.shutdown();
}ScheduledExecutorService can also schedule the task after some given fixed delay:
executorService.scheduleAtFixedRate(() -> {
// ...
}, 1, 10, TimeUnit.SECONDS);
executorService.scheduleWithFixedDelay(() -> {
// ...
}, 1, 10, TimeUnit.SECONDS);Here, the scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit ) method creates and executes a periodic action that is invoked firstly after the provided initial delay, and subsequently with the given period until the service instance shutdowns.
The scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit )