Differences and connections between threads and tasks

Source: Internet
Author: User

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"
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.