Several implementation and difference descriptions for the Java thread pool
Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import Java.util.Date;
Import java.util.List;
Import Java.util.Random;
Import java.util.concurrent.Callable;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future; The public class Testthreadpool {//-newfixedthreadpool is about the same as Cachethreadpool, and it can be reuse, but it is not possible to build a new thread at any time//-its uniqueness: at any point, 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 directly out of the pool//-unlike Cachethreadpool, Fixedthreadpool There is no idle mechanism (and possibly, but since the document is not mentioned, it must be very long, similar to relying on the upper layer of TCP or UDP//idle mechanisms, etc.), so fixedthreadpool is mostly for some very stable and regular concurrent threads, More for server//-from the source code of the method, the cache pool and the fixed pool call the same underlying pool, except for the different parameters://fixed pool thread number, and 0 seconds idle (no idle)//cache pool thread count support 0-integer.max_
VALUE (obviously completely does not consider the host's resources to withstand capacity), 60 seconds idle private static Executorservice Fixedservice = Executors.newfixedthreadpool (6);
-Cache pool, first see if there are any previously established threads in the pool, if there is, then reuse. If not, build a new thread to join the pool//-The buffer pool is typically used to perform some short-lived asynchronous tasks//So it is not used much in some connection-oriented daemon servers. -the thread that can reuse mustIs the timeout idle, the default timeout is 60s, longer than this idle, the thread instance will be terminated and removed from the pool.
Note that the thread that puts the Cachedthreadpool does not have to worry about its end, more than timeout inactive, and it will automatically be terminated.
private static Executorservice Cacheservice = Executors.newcachedthreadpool (); -a single thread that can only have one thread in any time pool with 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) private static Executorservice
Singleservice = Executors.newsinglethreadexecutor (); -Dispatch thread pool//-threads in this pool can be schedule sequentially delay execution, or periodically execute private static executorservice Scheduledservice = executors.newschedu
Ledthreadpool (10);
public static void Main (string[] args) {dateformat format = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
list<integer> customerlist = new arraylist<integer> ();
System.out.println (New Date ()) (Format.format);
Testfixedthreadpool (Fixedservice, customerlist);
System.out.println ("--------------------------");
Testfixedthreadpool (Fixedservice, customerlist);
Fixedservice.shutdown ();
System.out.println (Fixedservice.isshutdown ()); System.out.println ("----------------------------------------------------");
Testcachethreadpool (Cacheservice, customerlist);
System.out.println ("----------------------------------------------------");
Testcachethreadpool (Cacheservice, customerlist);
Cacheservice.shutdownnow ();
System.out.println ("----------------------------------------------------");
Testsingleservicethreadpool (Singleservice, customerlist);
Testsingleservicethreadpool (Singleservice, customerlist);
Singleservice.shutdown ();
System.out.println ("----------------------------------------------------");
Testscheduledservicethreadpool (Scheduledservice, customerlist);
Testscheduledservicethreadpool (Scheduledservice, customerlist);
Scheduledservice.shutdown (); public static void Testscheduledservicethreadpool (Executorservice service, list<integer> customerlist) {List& Lt
callable<integer>> listcallable = new arraylist<callable<integer>> (); for (int i = 0; i < i++) {callable<integer> callablE = new callable<integer> () {@Override public Integer call () throws Exception {return new Random (). NE
Xtint (10);
}
};
Listcallable.add (callable);
try {list<future<integer>> listfuture = Service.invokeall (listcallable);
for (future<integer> future:listfuture) {Integer id = future.get ();
customerList.Add (ID);
} catch (Exception e) {e.printstacktrace ();
} System.out.println (Customerlist.tostring ()); public static void Testsingleservicethreadpool (Executorservice service, list<integer> customerlist) {list<
callable<list<integer>>> listcallable = new arraylist<callable<list<integer>>> (); for (int i = 0; i < i++) {callable<list<integer>> callable = new Callable<list<integer>> ;() {@Override public list<integer> call () throws Exception {list<integer> List = getlist (New R
Andom (). Nextint (10)); BoOlean isstop = false; while (List.size () > 0 &&!isstop) {System.out.println (Thread.CurrentThread (). GetId () + "--sleep:1000"
);
Isstop = true;
} return list;
}
};
Listcallable.add (callable);
try {list<future<list<integer>>> listfuture = Service.invokeall (listcallable);
for (future<list<integer>> future:listfuture) {list<integer> List = Future.get ();
Customerlist.addall (list);
} catch (Exception e) {e.printstacktrace ();
} System.out.println (Customerlist.tostring ()); public static void Testcachethreadpool (Executorservice service, list<integer> customerlist) {list<callable
<List<Integer>>> listcallable = new arraylist<callable<list<integer>>> (); for (int i = 0; i < i++) {callable<list<integer>> callable = new Callable<list<integer>> ;() {@Override public list<integer>Call () throws Exception {list<integer> List = getlist (new Random (). Nextint (10));
Boolean isstop = false; while (List.size () > 0 &&!isstop) {System.out.println (Thread.CurrentThread (). GetId () + "--sleep:1000"
);
Isstop = true;
} return list;
}
};
Listcallable.add (callable);
try {list<future<list<integer>>> listfuture = Service.invokeall (listcallable);
for (future<list<integer>> future:listfuture) {list<integer> List = Future.get ();
Customerlist.addall (list);
} catch (Exception e) {e.printstacktrace ();
} System.out.println (Customerlist.tostring ()); public static void Testfixedthreadpool (Executorservice service, list<integer> customerlist) {list<callable
<List<Integer>>> listcallable = new arraylist<callable<list<integer>>> (); for (int i = 0; i < i++) {callable<list<integer>>callable = new Callable<list<integer>> () {@Override public list<integer> call () throws Exceptio
n {list<integer> List = getlist (new Random (). Nextint (10));
Boolean isstop = false; while (List.size () > 0 &&!isstop) {System.out.println (Thread.CurrentThread (). GetId () + "--sleep:1000"
);
Isstop = true;
} return list;
}
};
Listcallable.add (callable);
try {list<future<list<integer>>> listfuture = Service.invokeall (listcallable);
for (future<list<integer>> future:listfuture) {list<integer> List = Future.get ();
Customerlist.addall (list);
} catch (Exception e) {e.printstacktrace ();
} System.out.println (Customerlist.tostring ());
public static list<integer> getlist (int x) {list<integer> List = new arraylist<integer> ();
List.add (x);
List.add (x * x);
return list;
}
}
Using: Linkedblockingqueue implementation thread pool explanation
For example: Corepoolsize=3,maximumpoolsize=6,linkedblockingqueue (Ten)
// Rejectedexecutionhandler Default processing method is: Threadpoolexecutor.abortpolicy
//threadpoolexecutor executorservice = new Threadpoolexecutor (Corepoolsize, Maximumpoolsize, 1L, Timeunit.seconds, New linkedblockingqueue<runnable> (10) );
1. If the thread Cheng (that is, call Executorservice.execute) is not running at Linkedblockingqueue.init (10), the number of threads currently executing is: corepoolsize (3)
/ /2. If the Linkedblockingqueue.init (10) is exceeded and the number >=init (3) is exceeded, and is less than the init +maximumpoolsize. The number of threads currently started is: (the current number of threads,-init)
//3. If the number of threads that are invoked exceeds the Init (Ten) +maximumpoolsize, it is handled according to the rules of the Rejectedexecutionhandler.
About: Rejectedexecutionhandler Several default implementation explanation
By default: Threadpoolexecutor.abortpolicy, a handler rejected will throw the Run-time rejectedexecutionexception.
Rejectedexecutionhandler policy=new threadpoolexecutor.abortpolicy (); //In Threadpoolexecutor.callerrunspolicy, the thread invokes the execute itself that runs the task. This strategy provides a simple feedback control mechanism that can slow down the delivery of new tasks.
// policy=new threadpoolexecutor.callerrunspolicy (); //In Threadpoolexecutor.discardpolicy, tasks that cannot be performed will be deleted.
// policy=new threadpoolexecutor.discardpolicy (); //In Threadpoolexecutor.discardoldestpolicy, if the executing program has not been closed, the task at the head of the work queue will be deleted, and then retry the execution of the program (Repeat this procedure if it fails again).
// policy=new threadpoolexecutor.discardoldestpolicy ();
Above this Java thread pool several realization methods and the difference introduction is small arranges to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.