After the JAVA5, there is the function of the thread pool, before introducing the thread pool, let's take a simple look at the thread pool concept. Suppose I opened a consulting company, so every day there will be a lot of people come to ask questions, if I receive each, there must be a lot of people to line up, so the efficiency is very poor, I want to solve this problem, now I hired a few customer service, to a consultation, I assigned a customer service to receive him, another, I assigned a customer service ...... If the first customer service is over, I will let her receive the next consultant so that I can use the customer service to recycle. These customer service is like different threads, then the container that is loaded with these threads is called the thread pool.
The Executors tool class is used to create a thread pool that can specify the number of threads or not, or a thread pool of timers, which has the following common methods:
| Method Name |
function |
| Newfixedthreadpool (int nthreads) |
Create a fixed number of thread pools |
| Newcachedthreadpool () |
Create a cached thread pool |
| Newsinglethreadexecutor () |
Create a single thread |
| Newscheduledthreadpool (int corepoolsize) |
Creating a Timer thread pool |
2.1 Fixed number of thread pools
First look at the use of the Executors tool class:
Public class ThreadPool {//thread pool concept and use of the executors class Public Static void Main(string[] args) {//fixed thread pool: Create a fixed number of threads to perform a thread task, where three threads are createdExecutorservice ThreadPool = Executors.newfixedthreadpool (3); for(inti =1; I <=Ten; i++) {//Throw 10 missions into the pool Final inttask = i; Threadpool.execute (NewRunnable () {The //execute method means throwing a task into the pool, and the task is a runnable @Override Public void Run() { for(intj =1; J <=5; J + +) {Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +"Looping of"+ j +"for task of"+ Task); } } }); } System.out.println ("All of the tasks have committed!"); Threadpool.shutdown ();//Close after performing tasks//Threadpool.shutdownnow ();//Close now}}
As you can see from the code, with the Executors tool class, it's convenient for us to create a fixed number of threads that do the same task. Threadpool.execute means to remove a thread from the pool to perform the task, the above definition of three threads, so each will take three tasks to get the thread to execute, other tasks wait, after execution, then from the pool to take three tasks to execute, execute, then take three tasks, the last task three threads have a will rob to execute. So the number of threads is defined, each time the number of tasks is executed, because one thread is a task, and then another task is performed.
Because the result of this implementation is a bit more, it will not stick to the results, anyway, each time three tasks to execute, until the completion of 10 tasks.
2.2 Cache thread pool
The so-called cache thread pool, refers to the number of threads is not fixed, a task came, I opened a thread for its service, two tasks I opened two, n a task I opened N threads for its service. If there are only 1 tasks left now, after a period of time, the extra threads will be wiped out, leaving a thread to serve them. So you can rewrite the above code:
Public class ThreadPool {//thread pool concept and use of the executors class Public Static void Main(string[] args) {//cache thread pool //automatically according to the number of tasks to set the number of threads to service, more to increase the number of threads, less to reduce the number of threads //This seems to be the same as the general situation, because it is usually a thread to perform a task, but the advantage here is that if a thread dies, it will create a new one to perform the task .Executorservice ThreadPool = Executors.newcachedthreadpool (); for(inti =1; I <=Ten; i++) {//Throw 5 quests Final inttask = i; Threadpool.execute (NewRunnable () {//Throw a task into the pool, the task is a runnable @Override Public void Run() { for(intj =1; J <=5; J + +) {Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +"Looping of"+ j +"for task of"+ Task); } } }); } System.out.println ("All of the tasks have committed!"); Threadpool.shutdown ();//Close after performing tasks}}
When using the cache thread pool, the number of threads is automatically generated according to the number of tasks, that is, the thread follows the task. The result of the operation is also not affixed, a bit more.
Then create a single thread pool Newsinglethreadexecutor () wrote, the above method to get rid of the line, there is only one thread to perform 10 tasks, but this with our usual direct new A thread what is the difference? It also has the advantage that if the thread dies, it will automatically regenerate one, and our own new will not. Newsinglethreadexecutor () is a good choice if a thread dies and has to be re-created, which means that a thread is guaranteed to perform a task.
| 3. Thread Pool Start timer |
We can use the static method Newscheduledthreadpool (int corepoolsize) to define a timer thread pool, you can specify the number of threads. Then call the schedule method, pass in a runnable and timing time, see Code:
public class threadpool { public static void main (string[] args) {Executors.newscheduledthreadpool (3 ). Schedule (new Runnable () { @Over Ride public void run () {System.out.println (Thread.CurrentThread (). GetName () + " bomb ing "); }}, 2 , Timeunit.seconds); }}
Define three threads, there will be a first grab to the task execution in 2 seconds after execution. This just creates a task, what if we are going to use this thread pool to perform multiple tasks? Schedule can only pass in a runnable, which means only one task, the solution is the same as those above, the first to get the thread pool created, and then loop through the execution of schedule, each time a task can be:
Public class ThreadPool { Public Static void Main(string[] args) {//Get the timer thread poolScheduledexecutorservice ThreadPool = Executors.newscheduledthreadpool (3); for(inti =1; I <=5; i + +) {//Perform 5 missionsThreadpool.schedule (NewRunnable () {@Override Public void Run() {Try{Thread.Sleep ( +); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +"bombing"); } },2, timeunit.seconds); } }}
Because there are only 3 threads in the thread pool, but there are 5 tasks, 3 tasks are performed first, two tasks are left, and 2 threads are executed at random to see the results:
Pool-1-thread-3 bombing
Pool-1-thread-2 bombing
Pool-1-thread-1 bombing
Pool-1-thread-2 bombing
Pool-1-thread-3 bombing
What if I want to perform a task after 5 seconds and then execute it once every 2 seconds? We can call another method scheduleatfixedrate, which passes in a runnable, a timing time, and a time interval for each repetition, as follows:
public class threadpool { public static void main (string[] args) {Executors.newscheduledthreadpool (3 ). Scheduleatfixedrate (new Runnable () { @Override public void run () {System.out.println (Thread.CurrentThread (). GetName () + " bombing "); }}, 5 , 2 , Timeunit.seconds); }}
This can be performed after 5 seconds and is executed every 2 seconds later. This method has a flaw, that is, unable to set a specified point in time execution, the official JDK provides the solution is data.getTime()-System.currentTimeMillis() to get the relative time, and then put in the second parameter of the method above.
The use of the thread concurrency library is summed up so much.
Related reading: http://blog.csdn.net/column/details/bingfa.html
-Willing to share and progress together!
-More articles please see: http://blog.csdn.net/eson_15
The use of concurrent libraries for Java concurrency threads