The relationship between the thread and task of java multithreading:
1. The thread is independent from the task. The thread attaches to the task and drives the task execution. The real execution logic should be called "task ", threads and tasks are two different things. The logical code in the run () method is to execute the task. Therefore, every time a new thread object is created, the start () method of the thread object is used to drive the task, instead of directly calling the run () method of the thread object, we can see that the thread and task are completely different concepts.
2. in java, it is best to implement the runnable interface for a Thread class, which obviously separates threads from tasks, when passing parameters, the task parameters are directly transferred to the constructor of the thread class. In this way, not only can tasks inherit other classes, but also the Code logic is clearer.
One thread scheduler in the jvm is responsible for scheduling and allocating resources to threads in the jvm. If the Executor is used, the Executor can perform the functions of the thread scheduler, manage thread creation and scheduling. A thread pool is maintained in Executor, which eliminates the overhead of every thread creation. Improves thread reusability.
How to Use Excecutor:
ExecutorService service = Executors. newCachedThreadPool ();
Service.exe cute (thread );
This is only one of the usage methods. You can select different executors based on your own situation.
Author: "690360459-qq-com"