1, the Executor
Thread pool top-level interface. Define the method, void execute(Runnable). Method is a service method used to process a task. The caller provides an implementation of the Runnable interface that the thread pool executes through threads. The service method does not return a value. The run method in the Runnable interface returns no value. The -void execute(Runnable) method is used to start a thread task.
2, the ExecutorService
Subinterface of the Executor interface. A new service method, submit, is provided. There is a return value (type Future). The Submit method provides the Overload method. Where the parameter type is Runnable, do not need to provide a return value; There are arguments of type Callable that provide the return value after thread execution. Future is the return value of the Submit method. Represents the future, which is a consequence of the completion of thread execution. If the value is returned. Void execute(Runnable), Future Submit (Callable), Future Submit (Runnable) Running, ShuttingDown, Termitnaed Running – Thread pool being executed. Active status. ShuttingDown – Thread pool is being closed. Gracefully closed. Once in this state, the thread pool stops accepting new tasks, processes all received tasks, and closes the thread pool when it is finished. Terminated – The thread pool is closed.
3, Callable
Executable interface. Similar to the Runnable interface. Is also an interface that can start a thread. The method defined is call. The call method acts exactly like the run method in Runnable. The call method has a return value. Interface method: Object call(); Equivalent to the run method in the Runnable interface. The difference is that this method has a return value. A checked exception cannot be thrown. And the Runnable interface – Use Callable when you need to return a value or throw an exception, but optionally in other cases.
4, Executors
Tool type. Provides utility methods for Executor thread pools. Several thread pools can be provided quickly. Such as: fixed capacity, unlimited capacity, capacity 1, etc. Thread pools are a process-level heavyweight resource. The default life cycle is the same as the JVM. Thread pools are the default lifetime of thread pools when enabled until the JVM is shut down. If the shutdown method is called manually, the thread pool is automatically shutdown after all the tasks are executed. Start – Create a thread pool. End – The JVM shuts down or calls shutdown and processes all tasks. Utility types like Arrays, Collections, etc.
5, newFixedThreadPool
A thread pool of fixed capacity
A thread pool of fixed capacity. Active state and thread pool capacity are thread pools with upper limits. In all thread pools, there is a task queue. You use BlockingQueue as the vehicle for the task. When the number of tasks exceeds the capacity of the thread pool, the tasks that are not running are stored in the task queue. When there are idle threads, the tasks are automatically removed from the queue to execute. Usage Scenario: In most cases, the thread pool used is FixedThreadPool preferred. OS systems and hardware are capped by thread support. Thread pools cannot be arbitrarily provided without limit. The default maximum capacity of the thread pool is integer.max_value. Common thread pool capacity: PC-200. Server – 1000 to 10000 Queued tasks – Task queue completed tasks – End the task queue
/** * Thread pool * FixedThreadPool - Fixed capacity thread pool. When you create a thread pool, the capacity is fixed. * Build, provide maximum thread pool capacity * new XXXXX -> * ExecutorService - Thread pool service type. All thread pool types implement this interface. * Implementing this interface represents the ability to provide thread pooling. * shutdown - gracefully shutdown. Instead of forcibly closing the thread pool, recycle the resources in the thread pool. Instead of processing new tasks, the received tasks are processed * and then closed. * Executors - Executor tools class. Similar to the relationship between Collection and Collections. * It is easier to create several thread pools. * /
package concurrent.t08;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Test_02_FixedThreadPool {
public static void main(String[] args) {
ExecutorService service =
Executors.newFixedThreadPool(5);
for(int i = 0; i < 6; i++){
service.execute(new Runnable() {
@Override
public void run(a) {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " - test executor"); }}); } System.out.println(service); service.shutdown();// The resource has been reclaimed.
System.out.println(service.isTerminated());
// Whether the shutdown method has been called
System.out.println(service.isShutdown());
System.out.println(service);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
// service.shutdown();System.out.println(service.isTerminated()); System.out.println(service.isShutdown()); System.out.println(service); }}Copy the code
Results:
java.util.concurrent.ThreadPoolExecutor@42a57993[Running, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
false
true
java.util.concurrent.ThreadPoolExecutor@42a57993[Shutting down, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
pool-1-thread-2 - test executor
pool-1-thread-1 - test executor
pool-1-thread-5 - test executor
pool-1-thread-4 - test executor
pool-1-thread-3 - test executor
pool-1-thread-2 - test executor
true
true
java.util.concurrent.ThreadPoolExecutor@42a57993[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 6]
Copy the code
6 and the future
Future result, which represents the result after the execution of the thread task. The way to get the result of a thread’s execution is through the GET method. Get has no parameters and blocks until the thread finishes executing and gets the result. Get takes a parameter and blocks for a fixed length of time, waiting for the result after the thread completes execution. If the thread does not complete execution within the blocking duration, an exception is thrown. T get() T get(long, TimeUnit)
/** * thread pool * fixed capacity thread pool */
package concurrent.t08;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
public class Test_03_Future {
public static void main(String[] args) throws InterruptedException, ExecutionException {
/*FutureTask
task = new FutureTask<>(new Callable
() { @Override public String call() throws Exception { return "first future task"; }}); new Thread(task).start(); System.out.println(task.get()); * /
ExecutorService service = Executors.newFixedThreadPool(1);
Future<String> future = service.submit(new Callable<String>() {
@Override
public String call(a) {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("aaa");
return Thread.currentThread().getName() + " - test executor"; }}); System.out.println(future); System.out.println(future.isDone());// Check whether the thread ends and the task is complete. Whether the call method is complete
System.out.println(future.get()); // Get the return value of the call method.System.out.println(future.isDone()); }}Copy the code
Results:
java.util.concurrent.FutureTask@6d6f6e28
false
aaa
pool-1-thread-1 - test executor
true
Copy the code
7, CachedThreadPool
Cached thread pool. The capacity is unlimited (integer.max_value). Automatic capacity expansion. Capacity management policy: If the number of threads in the thread pool is insufficient for task execution, create a new thread. A new thread is created every time a new task cannot be processed in real time. When the idle time in the thread pool reaches a certain threshold (60 seconds by default), the thread is automatically released. Default thread idle for 60 seconds, automatic destruction. Application scenario: Internal application or test application. Internal applications, conditional internal data instant processing applications, such as: telecom platform at night to perform data sorting (be sure to finish all the work in a short time, and have enough confidence in hardware and software). Test the application and, while testing, try to get the maximum hardware or software load to provide guidance on FixedThreadPool capacity.
/** * Thread pool * Unlimited thread pool (maximum capacity defaults to integer.max_value) */
package concurrent.t08;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Test_05_CachedThreadPool {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
System.out.println(service);
for(int i = 0; i < 5; i++){
service.execute(new Runnable() {
@Override
public void run(a) {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " - test executor"); }}); } System.out.println(service);try {
TimeUnit.SECONDS.sleep(65);
} catch(InterruptedException e) { e.printStackTrace(); } System.out.println(service); }}Copy the code
Results:
java.util.concurrent.ThreadPoolExecutor@7f31245a[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
java.util.concurrent.ThreadPoolExecutor@7f31245a[Running, pool size = 5, active threads = 5, queued tasks = 0, completed tasks = 0]
pool-1-thread-5 - test executor
pool-1-thread-2 - test executor
pool-1-thread-4 - test executor
pool-1-thread-1 - test executor
pool-1-thread-3 - test executor
java.util.concurrent.ThreadPoolExecutor@7f31245a[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 5]
Process finished with exit code 0
Copy the code
8 ScheduledThreadPool.
Schedule the task thread pool. A thread pool that can automatically execute tasks according to schedule. ScheduleAtFixedRate (Runnable, start_limit, limit, timeUnit) Runnable – The task to be executed. Start_limit – Interval for executing the first task. Limit – Interval for executing multiple tasks. Timeunit – A unit of time between tasks. Usage scenario: Select DelaydQueue when planning tasks, such as data sorting in telecom industry, sorting every minute, sorting every hour, sorting every day, etc.
/** * thread pool * Schedule task thread pool. * /
package concurrent.t08;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test_07_ScheduledThreadPool {
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
System.out.println(service);
// Complete tasks on time. scheduleAtFixedRate(Runnable, start_limit, limit, timeunit)
// runnable - The task to be performed.
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run(a) {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch(InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); }},0.300, TimeUnit.MILLISECONDS); }}Copy the code
Results:
java.util.concurrent.ScheduledThreadPoolExecutor@14ae5a5[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
pool-1-thread-1
pool-1-thread-1
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
Copy the code
9 SingleThreadExceutor.
Single-capacity thread pool.
Usage scenario: Ensure the task sequence. Example: public channel chat in the game hall. Seconds kill.
/** * thread pool * Thread pool of capacity 1. Sequential execution. * /
package concurrent.t08;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Test_06_SingleThreadExecutor {
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
System.out.println(service);
for(int i = 0; i < 5; i++){
service.execute(new Runnable() {
@Override
public void run(a) {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " - test executor"); }}); }}}Copy the code
Results:
java.util.concurrent.Executors$FinalizableDelegatedExecutorService@14ae5a5
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor
pool-1-thread-1 - test executor
Copy the code
10, ForkJoinPool
Branch merge thread pools (mapDuce is a similar design idea). Suitable for complex tasks. Initialization thread capacity is related to the number of CPU cores. The content of the operation in the thread pool must be ForkJoinTask subtypes (RecursiveTask, RecursiveAction).
ForkJoinPool – Branches merge thread pools. Can recursively complete complex tasks. Tasks that require branching must be subtypes of the ForkJoinTask type. It provides the ability to branch and merge. The ForkJoinTask type provides two abstract subtypes: RecursiveTask a branch merge task that returns a result, and RecursiveAction a branch merge task that does not return a result. (Callable/Runnable) compute: specifies the execution logic of the task.
ForkJoinPool has no capacity. The default is always 1 thread. Automatically branch new child threads according to the task. When the child thread task ends, it is automatically merged. Automatic is implemented using the fork and Join methods. Application: mainly do scientific calculation or astronomical calculation. Data analytic
/** * thread pool * branches merge thread pools. * /
package concurrent.t08;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
public class Test_08_ForkJoinPool {
final static int[] numbers = new int[1000000];
final static int MAX_SIZE = 50000;
final static Random r = new Random();
static{
for(int i = 0; i < numbers.length; i++){
numbers[i] = r.nextInt(1000); }}static class AddTask extends RecursiveTask<Long>{ // RecursiveAction
int begin, end;
public AddTask(int begin, int end){
this.begin = begin;
this.end = end;
}
//
protected Long compute(a){
if((end - begin) < MAX_SIZE){
long sum = 0L;
for(int i = begin; i < end; i++){
sum += numbers[i];
}
// System.out.println("form " + begin + " to " + end + " sum is : " + sum);
return sum;
}else{
int middle = begin + (end - begin)/2;
AddTask task1 = new AddTask(begin, middle);
AddTask task2 = new AddTask(middle, end);
task1.fork();// is used to start a new task. It's branch work. Is to start a new thread task.
task2.fork();
// join - merge. Get the results of the task. This is a blocking method. You're bound to get the result data.
returntask1.join() + task2.join(); }}}public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
long result = 0L;
for(int i = 0; i < numbers.length; i++){
result += numbers[i];
}
System.out.println(result);
ForkJoinPool pool = new ForkJoinPool();
AddTask task = new AddTask(0, numbers.length); Future<Long> future = pool.submit(task); System.out.println(future.get()); }}Copy the code
Results:
499664397
499664397
Copy the code