Java Thread Pool

Source: Internet
Author: User

Executorservice:

 

Executorservice:

1. Define Thread class
Class handler implements runnable {
}

2. Create an executorservice Thread Pool
Executorservice = executors. newcachedthreadpool ();

Or

Int cpunums = runtime. getruntime (). availableprocessors ();
                // Obtain the number of CPUs of the current system
Executorservice = executors. newfixedthreadpool (cpunums * pool_size );
                // Executorservice generally flexibly defines the thread pool size based on system resources

3. Call the thread pool operation
Loop operation to become a daemon and put the new instance into the executor pool
      While (true ){
        Executorservice.exe cute (new handler (socket ));
          // Class handler implements runnable {
        Or
        Executorservice.exe cute (createtask (I ));
            // Private Static runnable createtask (final int taskid)
      }

Execute (runnable object) Method
Actually, the START () method is called for the runnable object.
(Of course there are some other background actions, such as queue, priority, idle timeout, and active activation)

Several different executorservice thread pool objects
1. newcachedthreadpool ()
-Cache pool, first check whether there are any threads in the pool that have been previously established. If yes, reuse it. If not, create a new thread to join the pool.
-Cache pools are usually used to execute asynchronous tasks with short lifetime.
Therefore, some connection-oriented daemon-type servers are rarely used.
-The Reuse thread must be a thread in the pool of timeout idle. The default timeout value is 60 s. If the idle length is exceeded, the thread instance will be terminated and removed from the pool.
  Note: The thread placed in the cachedthreadpool does not have to worry about its termination. If it exceeds the timeout, it is automatically terminated.

2. newfixedthreadpool
-The newfixedthreadpool is similar to the cachethreadpool and can be used for reuse, but cannot be used to create new threads at any time.
-Its uniqueness: at any time point, only a fixed number of active threads can exist. If a new thread needs to be created, it can only be placed in another queue for waiting, until the termination of a thread in the current thread is directly removed from the pool
-Unlike cachethreadpool, fixedthreadpool does not have an idle mechanism (it may also exist, but since the document is not mentioned, it must be very long, such as relying on the upper layer's TCP or UDP idle mechanism ), therefore, most fixedthreadpool targets some very stable and fixed regular concurrent threads, which are mostly used on servers.
-From the source code of the method, the cache pool and fixed pool call the same underlying pool, except that the parameters are different:
The number of threads in the fixed pool is fixed, and the value is 0 seconds idle (no idle)
The number of threads in the cache pool supports 0-integer.max_value (obviously, the host's resource capacity is not fully considered), and the idle is 60 seconds. 

3. scheduledthreadpool
-Scheduling Thread Pool
-The threads in this pool can be delay in sequence by schedule or periodical.

4. singlethreadexecutor
-Singleton thread. There can only be one thread in any time pool
-It uses the same underlying pool as the cache pool and fixed pool, but the number of threads is 1-seconds (no idle)

The preceding four thread pools use the default thread factory of executor to create threads. You can also define your own thread factory separately.
The following is the default thread factory code:
    

static class DefaultThreadFactory implements ThreadFactory {         static final AtomicInteger poolNumber = new AtomicInteger(1);         final ThreadGroup group;         final AtomicInteger threadNumber = new AtomicInteger(1);         final String namePrefix;          DefaultThreadFactory() {             SecurityManager s = System.getSecurityManager();             group = (s != null)? s.getThreadGroup() :Thread.currentThread().getThreadGroup();                       namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";         }          public Thread newThread(Runnable r) {     

Related Article

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.