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

  1. ExecutorService

    1. Basic method

      1. SubmitCallableMethod, returnFutureSubmit returns a value
      2. Execute: The command is executedRunnableMethod with no return value
      3. InvokeAny: Receives an includeCallableObject as a parameter. Calling this method does not returnFutureObject, but returns one of the collectionsCallableObject, and there is no guarantee that the result returned after the call is oneCallableThat’s all we know about itCallableThe execution of one of theCallableObject.
      4. InvokeAll: Invokes all that exist in the parameter setCallableObject, and returns a collection of Future objects from which each can be managedCallableThe execution result of.
      5. Shutdown: smooth shutdownExecutorService, when this method is called,ExecutorServiceStops 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.
    2. Rejection policies

      1. And throw ThreadPoolExecutor. AbortPolicy: discard taskRejectedExecutionExceptionThe exception.
      2. ThreadPoolExecutor. DiscardPolicy: discard task too, but I don’t throw an exception.
      3. ThreadPoolExecutor. DiscardOldestPolicy: discard queue in front of the task, the back of the mission
      4. ThreadPoolExecutor. CallerRunsPolicy: handle the tasks by the calling thread
    3. Blocking queue

      1. ArrayBlockingQueue: Array-based fifO queue, bounded
      2. LinkedBlockingQueue: A first-in, first-out queue based on a linked list, unbounded
      3. SynchronousQueue: An unbuffered wait queue, unbounded
      4. What is unbounded: if the capacity is not specified, the default isInteger.MAX_VALUE
    4. Common thread pool

      1. Executors. NewCachedThreadPool () : can be cached thread pool
      2. Executors. NewSingleThreadExecutor () : a single thread pool
      3. Executors. NewFixedThreadPool (3) : the fixed number of threads thread pool
      4. Executors. NewScheduledThreadPool (5) : fixed number of threads, and the regular support periodic tasks
      5. ThreadPoolExecutor(): Created manually
  2. Future

    1. Basic method

      1. 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
      2. Get (long timeout,TimeUnit Unit): Returns the result after waiting for a timeout
      3. Cancel (Boolean mayInterruptIfRunning): Can be used to stop a task if the task can be stopped (throughmayInterruptIfRunning), or false if the task is completed or stopped, or if the task cannot be stopped.
      4. IsDone (): Checks whether the current method is complete
      5. IsCancel (): Determines whether the current method is canceled