A, start
Multi-task parallel execution blocks until all execution is complete, and the number of concurrent tasks is controlled through the thread pool. The first part is code (listed according to the execution process), and the second part is related comments.
Create a Callable with returned data
public Callable<String> get(String key, Map<String, Object> params) {
return () -> {
System.out.println("Start enquiry =======" + params.toString());
Thread.sleep(500);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("Get task time :" + (currentTimeMillis1 - currentTimeMillis) + "ms");
return key + "Ha, ha, ha, ha.";
};
}
Copy the code
Three, circular call creationCallable<String>
List<Callable<String>> tasks = new ArrayList<>();
for (int i = 0; i < 30; i++) {
// ... params
Callable<String> callable = mSmsStatisticsService.get(i + "key", params);
tasks.add(callable);
}
Copy the code
Create a thread pool
/** * corePoolSize: specifies the number of core threads. * maximumPoolSize: The maximum number of threads allowed to be created in the thread pool. * keepAliveTime: timeout for non-core threads to be idle. Any more than that is recycled. * TimeUnit: keepAliveTime TimeUnit. * workQueue: indicates a task queue. * ThreadFactory: ThreadFactory, used to create threads. * RejectedExecutionHandler: saturation policy. * * ThreadPoolExecutor(int corePoolSize, * int maximumPoolSize, * long keepAliveTime, * TimeUnit unit, * BlockingQueue
workQueue, * ThreadFactory threadFactory, * RejectedExecutionHandler handler) */
ExecutorService executorService = new ThreadPoolExecutor(5.32.0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
r -> {
Thread thread = new Thread(r);
// thread.setName("sdwfqin");
return thread;
}, new ThreadPoolExecutor.AbortPolicy());
Copy the code
Start the thread and get the returned data
List<String> resultList = new ArrayList<>();
// Start the thread and get the returned data
List<Future<String>> futures = executorService.invokeAll(tasks);
for (Future<String> future : futures) {
resultList.add(future.get());
}
Copy the code
Close the thread pool
executorService.shutdown();
Copy the code
Vii. Explanation of the API mentioned above
-
ExecutorService
-
Basic method
- Submit
Callable
Method, returnFuture
Submit returns a value - Execute: The command is executed
Runnable
Method with no return value - InvokeAny: Receives an include
Callable
Object as a parameter. Calling this method does not returnFuture
Object, but returns one of the collectionsCallable
Object, and there is no guarantee that the result returned after the call is oneCallable
That’s all we know about itCallable
The execution of one of theCallable
Object. - InvokeAll: Invokes all that exist in the parameter set
Callable
Object, and returns a collection of Future objects from which each can be managedCallable
The execution result of. - Shutdown: smooth shutdown
ExecutorService
, when this method is called,ExecutorService
Stops receiving new tasks and waits for submitted tasks (both commit in progress and commit not executed) to complete. The thread pool is closed when all commit tasks are completed.
- Submit
-
Rejection policies
- And throw ThreadPoolExecutor. AbortPolicy: discard task
RejectedExecutionException
The exception. - ThreadPoolExecutor. DiscardPolicy: discard task too, but I don’t throw an exception.
- ThreadPoolExecutor. DiscardOldestPolicy: discard queue in front of the task, the back of the mission
- ThreadPoolExecutor. CallerRunsPolicy: handle the tasks by the calling thread
- And throw ThreadPoolExecutor. AbortPolicy: discard task
-
Blocking queue
- ArrayBlockingQueue: Array-based fifO queue, bounded
- LinkedBlockingQueue: A first-in, first-out queue based on a linked list, unbounded
- SynchronousQueue: An unbuffered wait queue, unbounded
- What is unbounded: if the capacity is not specified, the default is
Integer.MAX_VALUE
-
Common thread pool
- Executors. NewCachedThreadPool () : can be cached thread pool
- Executors. NewSingleThreadExecutor () : a single thread pool
- Executors. NewFixedThreadPool (3) : the fixed number of threads thread pool
- Executors. NewScheduledThreadPool (5) : fixed number of threads, and the regular support periodic tasks
- ThreadPoolExecutor(): Created manually
-
-
Future
-
Basic method
- Get: Returns a result when the task is finished. If the work is not finished when called, the thread will be blocked until the task is finished
- Get (long timeout,TimeUnit Unit): Returns the result after waiting for a timeout
- Cancel (Boolean mayInterruptIfRunning): Can be used to stop a task if the task can be stopped (through
mayInterruptIfRunning
), or false if the task is completed or stopped, or if the task cannot be stopped. - IsDone (): Checks whether the current method is complete
- IsCancel (): Determines whether the current method is canceled
-