In-depth understanding of concurrency (1), in-depth understanding of concurrency (

Source: Internet
Author: User

In-depth understanding of concurrency (1), in-depth understanding of concurrency (

1. Why concurrency?
Perhaps the first reason we think of is to make the program run faster. Indeed, for a multi-processor machine, each task is allocated to multiple CPUs using concurrency, it enables faster program execution.
However, when a concurrent program is run on a single processor machine, the cost of context switching (the event that occurs when the CPU control is transferred from the running task to another ready task) is, the overhead is even greater than the sequential execution. That is not to say that concurrency does not work for a single processor?
In fact, if there is no concurrency, blocking may cause the entire program to stop. for Android, ANR may occur. however, when concurrency is introduced, other tasks in the program can continue to be executed when a task is blocked.

2. How is concurrency implemented in JAVA?
JAVA introduces the thread mechanism, that is, creating a task in a single process represented by the execution program. in addition, the JAVA thread mechanism is preemptible, that is, the thread is periodically interrupted by the thread scheduler, and the context is switched to another thread to provide a time slice for each thread, so that each thread is allocated a reasonable amount of time to drive its tasks. in this way, every subtask in the program is driven by the execution thread.

3. Define a task in JAVA:
1. Implement the Runnable interface and compile the run () method. submit the Runnable object to the Thread constructor, call the start () method of the Thread class, and start the task. (Note: although you can also directly call the Runnable run () method, if you use this method, it is relative to calling a method and does not involve multithreading .)

Runnable run = new Runnable(){    public void run(){    }}new Thread(run).start();

2. inherit the Thread class directly, and then override the run () method in the Thread class.

class run extends Thread{    public void run(){    }}

4. Why do I need a thread pool?
If the number of threads created with the Thread is large and each Thread executes the task for a short time, frequent creation will greatly reduce the system efficiency, because frequent Thread creation and Thread destruction require overhead.
If a thread pool is introduced, you can reuse existing threads to reduce the overhead of object creation and destruction, and manually control the maximum number of concurrent tasks to avoid excessive competition.
Java provides four thread pools through Executors:

public static ExecutorService newFixedThreadPool(int nThreads) {    return new ThreadPoolExecutor(nThreads, nThreads,                                  0L, TimeUnit.MILLISECONDS,                          new LinkedBlockingQueue<Runnable>());}public static ExecutorService newSingleThreadExecutor() {    return new FinalizableDelegatedExecutorService        (new ThreadPoolExecutor(1, 1,                                0L, TimeUnit.MILLISECONDS,                          new LinkedBlockingQueue<Runnable>()));}public static ExecutorService newCachedThreadPool() {    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,                                  60L, TimeUnit.SECONDS,                            new SynchronousQueue<Runnable>());}

From their implementation, we can see that they are all implemented:

public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue<Runnable> workQueue) {        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,Executors.defaultThreadFactory(), defaultHandler);    }

Where
• CorePoolSize: the size of the core pool. This parameter is closely related to the implementation principle of the thread pool described later. After a thread pool is created, by default, there are no threads in the thread pool. Instead, the thread is created to execute the task only after a task arrives, unless prestartAllCoreThreads () or prestartCoreThread () is called () from the names of the two methods, we can see that it is the meaning of the pre-created thread, that is, to create a corePoolSize thread or a thread before the task arrives. By default, after a thread pool is created, the number of threads in the thread pool is 0. When a task comes, a thread is created to execute the task, when the number of threads in the thread pool reaches corePoolSize, the tasks that arrive will be placed in the cache queue;
• MaximumPoolSize: Maximum number of threads in the thread pool. This parameter is also a very important parameter, indicating the maximum number of threads that can be created in the thread pool;
• KeepAliveTime: indicates the maximum duration for a thread to terminate when no task is executed (that is, when the run () method returns, it is called the end ). By default, keepAliveTime takes effect only when the number of threads in the thread pool is greater than corePoolSize until the number of threads in the thread pool is not greater than corePoolSize, that is, when the number of threads in the thread pool is greater than corePoolSize, if the idle time of a thread reaches keepAliveTime, it will be terminated until the number of threads in the thread pool does not exceed corePoolSize. However, if the allowCoreThreadTimeOut (boolean) method is called and the number of threads in the thread pool is not greater than the corePoolSize, The keepAliveTime parameter also takes effect until the number of threads in the thread pool is 0;
• Unit: The time unit of the keepAliveTime parameter. There are 7 values and 7 static attributes in the TimeUnit class:

TimeUnit. DAYS; // day
TimeUnit. HOURS; // hour
TimeUnit. MINUTES; // minute
TimeUnit. SECONDS; // second
TimeUnit. MILLISECONDS; // millisecond
TimeUnit. MICROSECONDS; // subtle
TimeUnit. NANOSECONDS; // Nanosecond
• WorkQueue: a blocking queue used to store tasks waiting for execution. The selection of this parameter is also very important and will have a significant impact on the running process of the thread pool. Generally, the blocking queue here has the following options:
ArrayBlockingQueue;
LinkedBlockingQueue;
SynchronousQueue;

Therefore, if the thread pool provided by Executors cannot meet the requirements, you can construct ThreadPoolExecutor as needed.

For more detailed parsing of the ThreadPoolExecutor class, see:
Http://www.cnblogs.com/dolphin0520/p/3932921.html

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.