Some thoughts on concurrency programming in Java

Source: Internet
Author: User

1. Threads and Runnables

All modern operating systems support concurrency through processes and threads. A process is an instance of a program that normally runs independently of each other, for example, if you start a Java program, the operating system generates a new process that executes in parallel with other programs. Inside these processes, we use threads to execute code concurrently, so we can make the most of the cores available to the CPU. Java starts executing threads from JDK1.0. Before starting a new thread, you must specify the code that is executed by this thread, often called a task. This can be accomplished by implementing Runnable: a function interface that defines a method without a return value without parameters run() , as shown in the following code:

Runnable task = ()- {     //jdk 1.8 Lambda    expression = thread.currentthread (). GetName ();    System.out.println ("Hello" +new  Thread (Task); Thread.Start (); System.out.println ("done!");

2. Use of the Java thread pool

The above inherits the thread class and implements the Runnable interface, which can implement multithreading. However, if the number of concurrent threads is large, and each thread executes a short task, it is done, so that creating threads frequently can greatly reduce the efficiency of the system because it takes time to create threads and destroy threads frequently. So is there a way to enable a thread to be reused, to perform a task, not to be destroyed, but to continue to perform other tasks? this can be achieved through the thread pool in Java. today we will explain in detail the Java thread pool, first we start from the core of the Threadpoolexecutor class method, and then the implementation of the principle, and then give its use example, finally discussed how to reasonably configure the size of the thread pool.

Java Threadpoolexecutor class, Java: The Uitl.concurrent.ThreadPoolExecutor class is the most core class in the thread pool, so if you want a thorough understanding of the thread pools in Java, you must first understand this class. Let's look at the specific implementation of the Threadpoolexecutor class source.

 Public classThreadpoolexecutorextendsAbstractexecutorservice { PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,Longkeepalivetime,timeunit Unit, Blockingqueue<Runnable>workQueue);  PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,Longkeepalivetime,timeunit Unit, Blockingqueue<Runnable>workqueue,threadfactory threadfactory);  PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,Longkeepalivetime,timeunit Unit, Blockingqueue<Runnable>Workqueue,rejectedexecutionhandler handler);  PublicThreadpoolexecutor (intCorepoolsize,intMaximumpoolsize,Longkeepalivetime,timeunit Unit, Blockingqueue<Runnable>workqueue,threadfactory Threadfactory,rejectedexecutionhandler handler); }

As you can tell from the code above, Threadpoolexecutor inherits the Abstractexecutorservice class and provides four constructors, in fact, by observing the concrete implementation of each constructor's source code, It is found that the first three constructors are initialized by the fourth constructor that is called. The following explains the meanings of each parameter in the constructor:

coorpoolsize: the size of the core pool, this parameter is very much related to the implementation principle of the thread pool described later. After the thread pool has been created, by default, there are no threads in the thread pools, instead of waiting for a task to be created to perform the task, unless the prestartallcorethreads () or Prestartcorethread () method is called. As you can see from the names of these 2 methods, the meaning of pre-created threads is to create corepoolsize threads or a thread before a task arrives. By default, after the thread pool has been created, the number of threads in the threads pools is 0, and when a task comes, a thread is created to perform the task, and when the number of threads in the thread pool reaches corepoolsize, the incoming task is placed in the cache queue ; Maximumpoolsize: The maximum number of threads in a thread pool, this parameter is also a very important parameter, which represents the maximum number of threads that can be created in a thread pool; KeepAliveTime: Indicates how long it will take for the threads to be terminated without a task execution. By default, KeepAliveTime only works if 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 a thread is idle for KeepAliveTime, it terminates 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 corepoolsize, the KeepAliveTime parameter also works until the number of threads in the thread pool is 0 ; Unit parameter: KeepAliveTime time unit with 7 values, 7 static properties in the Timeunit class:

Timeunit.days;               // days timeunit.hours;             // hours Timeunit.minutes;           // minutes Timeunit.seconds;           // seconds Timeunit.milliseconds;      // milliseconds Timeunit.microseconds;      // Subtle Timeunit.nanoseconds;       // na-Sec

WorkQueue: A blocking queue that stores the tasks waiting to be executed, and the choice of this parameter is also important to have a significant impact on the running process of the thread pool, in general, where the blocking queue has the following options:

 

A few thoughts on Java concurrency programming

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.