Java Code import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.threadfactory; public class testthreadpool { public static void main (String Args[]) throws InterruptedException { executorservice exec = executors.newfixedthreadpool (10, new mythreadfactoy ()); for (Int index = 0; index < 10; index++) { runnable run = new runnable () { public void run () { long time = (Long) (Math.random () * 1000); System.out.println ("sleeping " + time + "MS" + "/" + Thread.CurrentThread (). GetName ()); try { thread.sleep (time); } catch (interruptedexception e) { } } }; exec.execute (run); } // must shutdown exec.shutdown (); } } class mythreadfactoy implements threadfactory { @Override public thread newthread (runnable r) { thread t =&nbSp;new thread (r); return t; } }
Executorservice steps to establish multithreading:
1. Defining Thread Classes
|
Class Handler implements runnable{ }
|
2. Establishing a Executorservice thread pool
|
Executorservice Executorservice = Executors.newcachedthreadpool ();
Or
int cpunums = Runtime.getruntime (). Availableprocessors (); Gets the number of CPUs for the current system Executorservice executorservice =executors.newfixedthreadpool (cpunums * pool_size); Executorservice typically flexibly defines the thread pool size based on system resource conditions
|
3. Invoking a thread pool operation
|
Cycle operations, become daemon, put new instances into the executor pool while (true) { Executorservice.execute (new Handler (socket)); Class Handler implements runnable{ Or Executorservice.execute (CreateTask (i)); private static Runnable createtask (final int TaskID) }
Execute (Runnable object) method is actually calling the start () method on the Runnable object (There are, of course, other background actions, such as queue, priority, IDLE timeout,active activation, etc.)
|
Several different executorservice thread pool objects
1.newCachedThreadPool ()
|
-Cache pool (a thread pool that creates new threads as needed), first to see if there are any previously established threads in the pool, if so, to reuse, and if not, to build a new thread to join the pool, which typically improves program performance. -cache pools are typically used to perform some short-lived asynchronous tasks Therefore, it is not much used in some connection-oriented daemon servers. -the thread that can be reuse, must be in timeout idle in the pool thread, the default timeout is 60s, more than this idle time, the thread instance will be terminated and removed from the pool. Note that the thread that is put into the cachedthreadpool does not have to worry about its end, exceeding timeout inactivity, which is automatically terminated.
|
2. Newfixedthreadpool
|
-newfixedthreadpool is similar to Cachethreadpool and can be reused, but cannot be built on new threads at any time. -Its uniqueness: At any point in time, there can be at most a fixed number of active threads, and if a new thread is to be established, it can only wait in another queue until a thread in the current thread terminates and is moved out of the pool directly. -unlike Cachethreadpool, Fixedthreadpool does not have an idle mechanism (possibly, but since the document is not mentioned, it must be very long, similar to the TCP or UDP idle mechanism that relies on the upper layer), So Fixedthreadpool most for some very stable and fixed regular concurrent threads, more for the server -From the source of the method, the cache pool and the fixed pool call the same underlying pool, except that the parameters are different: Fixed pool thread count, and is 0 seconds idle (no idle) Cache Pool Threads Support 0-integer.max_value (obviously not considering the host's resource tolerance), 60 seconds idle
|
3.ScheduledThreadPool
|
-Scheduling thread pool -The thread in this pool can be executed by schedule, or cycle execution
|
4.SingleThreadExecutor
|
-Single thread, only one thread in any time pool -Use the same underlying pool as the cache pool and the fixed pool, but the number of threads is 1-1, 0 seconds idle (no idle)
|
The above four thread pools use Executor's default thread factory to build threads, or you can define your own thread factory individually
The following is the default thread factory code: http://www.my400800.cn
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) { Thread t = new Thread (group, R,nameprefix + threadnumber.getandincrement (), 0); if (T.isdaemon ()) T.setdaemon (FALSE); if (t.getpriority ()! = thread.norm_priority) T.setpriority (thread.norm_priority); return t; } }
|
You can also define your own threadfactory, adding parameters to the pool
public static Executorservice Newcachedthreadpool (Threadfactory threadfactory) {
|
Executor's Execute () method
The Execute () method joins the Runnable instance to the pool and makes some pool size calculations and priority processing
The Execute () method itself is defined in the executor interface, and there are multiple implementation classes that define different execute () methods
such as the Threadpoolexecutor class (Cache,fiexed,single Three pools are called it), the Execute method is as follows:
public void Execute (Runnable command) { if (command = = null) throw new NullPointerException (); if (poolsize >= corepoolsize | |!addifundercorepoolsize (command)) { if (runstate = = RUNNING && workqueue.offer (command)) { if (runstate! = RUNNING | | poolsize = = 0) ensurequeuedtaskhandled (command); } else if (!addifundermaximumpoolsize (command)) Reject (command); is shutdown or saturated } }
|