Usually use the thread pool

After reading this article you will know the following three points:

1. Process - Thread briefly

what 2.java thread pool is, what type, what role are the

advantages of using a thread pool in 3.

 
1. Process - thread brief

process

What is the process?

The process is run in the event a computer program on a data set is the basic unit of scheduling system for resource allocation, it is the underlying operating system architecture. Simply put: the process is an application that runs in the process is an entity, each process has its own address space. For example, we clicked on the QQ, to start a process, the operating system will assign a separate address space for the process, when we click on the browser, which in turn started a process, the operating system for a new process to allocate a new independent address space.

Thread

What is the thread of it?

A thread is the smallest unit of an operating system capable of operation scheduled to be included in the process, the actual operation of the unit process. A process has at least one thread. A thread refers to a single control flow of a process sequence, a process can be complicated by a plurality of threads, each thread in parallel to perform different tasks. Note: The thread does not own its own system resources, has only a little in the operation of essential resources, but it may have in place, blocking and belong to the same process other threads share the process have all the resources, threads, running three basic status.

Also: In the SunOS Unix System and it is also referred to as lightweight processes, but more lightweight process refers to kernel threads, and the user thread called thread.
What 2.java thread pool is, what type, what role are

Thread pool is a multithreaded processing form, in the process of adding the task queue, and then start these tasks automatically after the creation of threads, each thread using the default stack size to default priority run, and impose multithreading unit, if a managed code in the idle thread, the thread pool thread to be inserted so that all other auxiliary processor remains busy. If all the thread pool is always kept busy, but the queue contains pending work, the number of helper threads thread pool will never exceed the maximum value over time. Thread exceeds the maximum value can be queued, but they have to wait until after the completion of another thread to start.

java thread pool inside the top-level interface is Executor, Executor is not a thread pool, but only one thread of execution tool, but the real thread pool is ExecutorService.

What have java in the thread pool?

1.newCachedThreadPool create a process that can be cached thread pool

2.newFixedThreadPool create a fixed-size thread pool

3.newScheduledThreadPool create a fixed-size thread pool

4.newSingleThreadExecutor create a single-threaded thread pool

below one analysis:

1.newCachedThreadPool, it is a a variable number of kinds of threads the thread pool, and the maximum number of threads Integer.MAX_VALUE, this number is great, a thread pool may be cached, if the thread pool is longer than the processing needs, flexibility recovered idle thread, if not recycled, the new thread. But idle threads in the pool has a timeout limit, when the timeout period is 60 seconds, more than 60 seconds of idle thread will be recovered. Calls to execute will reuse previously constructed threads (if the thread is available). Such thread pool more suitable for the implementation of a large number of less time-consuming task, when the whole thread pool are idle, the thread pool thread will time-out is stopped.

Example code:

    public class PoolExecutorTest {
     
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            
            ExecutorService mCachelThreadPool = Executors.newCachedThreadPool();
            
            for(int i = 0;i < 7;i++ ) {
                final int index = i;
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mCachelThreadPool.execute(new Runnable() {
                    
                    @Override
                    public void run() {
                        System.out.println ( "first" + index + "threads" + Thread.currentThread () getName ().);
                    }
                });
                
            }
            
     
        }
     
    }

The output:

can be seen from the results, the second task performing when the first task has been completed, the thread used to perform the first task will be complex, not every new thread.

2.newFixedThreadPool create a specified number of worker threads the thread pool, whenever you submit a task to create a worker thread, when the thread is in an idle state, they will not be recovered, unless the thread pool is closed, if the number of worker threads reach the initial thread pool maximum number of tasks will be submitted into the queue to the pool (no size limit) in. Since newFixedThreadPool only the core kernel threads and these threads will not be recovered, so it is more rapid end of the corresponding request outside.

Code Example:

    public class PoolExecutorTest {
     
        public static void main (String [] args) throws InterruptedException {
            // the TODO Auto-Generated Method Stub
            // set the maximum number of threads 5
            ExecutorService mFixedThreadPool = Executors.newFixedThreadPool(5);
            
            for(int i = 0;i < 7;i++ ) {
                final int index = i;
                mFixedThreadPool.execute(new Runnable() {
                    
                    @Override
                    public void run() {
                        System.out.println("时间是:"+System.currentTimeMillis()+"第" +index +"个线程" +Thread.currentThread().getName());
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }    
                     }
                });
                
            }
            
     
        }
     
    }

The output:

since the maximum thread 5, so that when executing the threads 5, after waiting for two seconds, after the two execution threads.

3.newScheduledThreadPool create a thread pool, its core is a fixed number of threads, rather than a core number of threads is no limit, and will be immediately recovered when the non-core thread is idle, it can be scheduled to run periodically or after a specified delay command performed. Such thread pool is mainly used to perform repetitive tasks scheduled tasks having a fixed period.

Delayed execution example code:

    public class PoolExecutorTest {
     
        public static void main (String [] args) throws InterruptedException {
            // Generated Method Stub the TODO Auto-
            
            cores are disposed in the pool @ 2
            The ScheduledExecutorService mScheduledThreadPool = Executors.newScheduledThreadPool (2);  
            the System .out.println ( "time now:" + System.currentTimeMillis ());
            mScheduledThreadPool.schedule (the Runnable new new () {
                
                @Override
                RUN void public () {
                    // the TODO Auto-Generated Stub Method
                    System.out.println ( "time now:" + System.currentTimeMillis ());
                    
                }
            }, 4, TimeUnit.SECONDS); // set the delay here 4 second execution
            
     
        }
     
    }

result of the execution of the following:

the error can be ignored, actual delay of 4 seconds results do performed.

Periodically execute the example code

    public class PoolExecutorTest {
     
        public static void main (String [] args) throws InterruptedException {
            // the TODO Auto-Generated Method Stub
            
            // number of cores is disposed in the pool 2
            The ScheduledExecutorService mScheduledThreadPool = Executors.newScheduledThreadPool (2);  
            the System. out.println ( "the time now:" + System.currentTimeMillis ());
            mScheduledThreadPool.scheduleAtFixedRate (the Runnable new new () {
                
                @Override
                public void RUN () {
                    // the TODO Auto-Generated Stub Method
                    System.out.println ( "time now:" + System.currentTimeMillis ());
                    
                }
            }, 2, 3, TimeUnit.SECONDS); // set here performed every 3 seconds after a 2 second delay time
            
     
        }
     
    }

result of the execution of the following:

may be found indeed performed by 2 seconds after every 3 seconds, the program has been executed not exit down.

4.newSingleThreadExecutor Such internal thread pool has only one core thread to unbounded queue to execute the thread, which makes the problem does not need to deal with these tasks synchronization between threads, it ensures that all tasks are in the same order in a thread execution, and can not at any given time there are multiple threads are active.

Sample code:

    public class PoolExecutorTest {
     
        public static void main (String [] args) {throws InterruptedException
            // TODO Auto-generated method stub
            
            ExecutorService mSingleThreadPool = Executors.newSingleThreadExecutor();     
            for(int i = 0;i < 7;i++) {
                final int number = i;
                mSingleThreadPool.execute(new Runnable() {
                    
                    @Override
                    public void run() {
                        System.out.println("现在的时间:"+System.currentTimeMillis()+"第"+number+"个线程");
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        
                    }
                });
                
            }
     
        }
     
    }

Result of the execution of the following:

may be found to be executed in sequence to the above six threads.
3. The advantage of using the thread pool

1 reused thread pool thread, avoid the creation and destruction caused by thread-locking performance overhead

maximum number of concurrent 2. Effective control of the thread pool to avoid seize large amounts of system resources between threads obstruction

3. enables simple management of threads, and to provide some specific operations, such as: to provide regular, periodic, single-threaded, concurrent control and other functions
----------------
copyright Disclaimer: this article is CSDN blogger "true Crimson Knights' original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/qq_33453910/article/details/81413285

Guess you like

Origin www.cnblogs.com/chuang-sharing/p/11653346.html