There are two ways to implement multithreading in Java, inherit thread, implement Runnable,
But after JDK1.5, there is a new way to implement the Callable<v> interface
PackageTest2016.demo;Importjava.util.ArrayList;Importjava.util.List;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.CompletionService;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorCompletionService;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future; Public classDemo9 { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {executorservice executors= Executors.newfixedthreadpool (5); LongStart =System.currenttimemillis (); /**list<future<integer>> futures = new arraylist<future<integer>> (10); for (int i = 1; i <=; i++) {Futures.add (Executors.submit (New MyTask1 (i))); } for (future<integer> future:futures) {Integer result = Future.get (); System.out.println ("Thread:" + result + "execution completed!!!");}*/Completionservice<Integer> completionservices =NewExecutorcompletionservice<integer>(executors); for(inti = 1; I <= 10; i++) {Completionservices.submit (NewMyTask1 (i)); } for(inti = 1; I <= 10; i++) {Integer result=Completionservices.take (). get (); System.out.println ("Threads:" + result + "Execution completed!!!"); } LongEnd =System.currenttimemillis (); System.out.println ("Total Duration:" + (End-start)/1000 + "SEC"); Executors.shutdown (); Thread pool must be closed manually}}classMyTask1ImplementsCallable<integer> { Private intTasknum; PublicMyTask1 (intnum) { This. Tasknum =num; } @Override PublicInteger Call ()throwsException {System.out.println ("Thread of Execution:" +tasknum); Thread.Sleep (1000); returnTasknum; } }
Execution Result:
Future:
Completionservice:
Use the future interface to get the status of the task, followed by the execution order of the thread to return the result, namely: Execute first get the result
Use the completionservice interface to get the status of the task and get the corresponding result in the order of execution completion, i.e.: End first to get the result
EG: If two threads, thread 1 executes first, thread 2 executes, but thread 1 finishes executing requires 100s, thread 2 finishes executing 1s is required,
If you use the future to get the result status:
Thread 1 complete!!!
Thread 2 complete!!!
If you use Completionservice to get the result status:
Thread 2 complete!!!
Thread 1 complete!!!
Attached:Executorservice Interface (Source: public interface Executorservice extends executor{}) create thread pool mode:
Threadpoolexecutor Implementing a thread pool
The Threadpoolexecutor class is an implementation class for the Executorservice interface
Source: public class Threadpoolexecutor extends Abstractexecutorservice {}
Public abstract class Abstractexecutorservice implements Executorservice {}
PackageTest2016.demo;ImportJava.util.concurrent.ArrayBlockingQueue;ImportJava.util.concurrent.ThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit; Public classDemo8 { Public Static voidMain (string[] args) {/*** corepoolsize: Thread pool maintains minimum number of threads * maximumpoolsize: Thread pool maintains maximum number of threads * KeepAliveTime: Thread pool maintenance threads allowed Idle time * Unit: Thread pool maintains the unit of idle time allowed by thread * WorkQueue: The buffer queue used by the threads pool * Handler: The thread pool's processing policy for rejected tasks * */Threadpoolexecutor Executor=NewThreadpoolexecutor (Timeunit.nanoseconds,NewArrayblockingqueue<runnable> (15)); for(inti = 1; I <= 50; i++) {MyTask MyTask=NewMyTask (i); Executor.execute (MyTask); System.out.println ("Thread pool Threads:" +executor.getpoolsize () + ", Number of tasks waiting to be executed in queue:" +executor.getqueue (). Size ()+ ", the number of other tasks performed:" +Executor.getcompletedtaskcount ()); } executor.shutdown (); }}classMyTaskImplementsRunnable {Private intTasknum; PublicMyTask (intnum) { This. Tasknum =num; } @SuppressWarnings ("Static-access") Public voidrun () {System.out.println ("Executing task:" +tasknum); Try{Thread.CurrentThread (). Sleep (3000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Task" +tasknum+ "Execution Complete"); } }
1, Corepoolsize: The size of the core pool, this parameter with the thread pool described in the following implementation principle has a very big relationship.
After creating the thread pool, by default, there are no threads in the thread pools, but wait for a task to come before creating the thread to perform the task.
Unless you call the Prestartallcorethreads () or the Prestartcorethread () method, you can see from the names of these 2 methods that the pre-created thread means,
That is, create corepoolsize threads or a thread before a task arrives. By default, after a thread pool has been created, the number of threads in the thread pools is 0, and when a task comes up,
A thread is created to perform the task, and when the number of threads in the thread pool reaches corepoolsize, the incoming task is placed in the cache queue;
2, Maximumpoolsize: Thread pool Maximum number of threads, this parameter is also a very important parameter, it represents the maximum number of threads in a thread pool can be created;
3. KeepAliveTime: Indicates the maximum length of time a thread will be terminated without a task executing.
By default, KeepAliveTime only works if the number of threads in the thread pool is greater than corepoolsize, until the number of threads in the thread pool is not greater than corepoolsize.
That is, when the number of threads in the thread pool is greater than corepoolsize, if a thread is idle for KeepAliveTime, it terminates until the number of threads in the thread pool does not exceed corepoolsize.
But if the Allowcorethreadtimeout (Boolean) method is called,
When the number of threads in a thread pool is not greater than corepoolsize, the KeepAliveTime parameter also works until the number of threads in the thread pool is 0;
4, Unit: The time Unit of parameter KeepAliveTime, there are 7 kinds of values, there are 7 kinds of static properties in Timeunit class:
Timeunit.days; // days timeunit.hours; // hours Timeunit.minutes; // minutes Timeunit.seconds; // seconds Timeunit.milliseconds; // milliseconds Timeunit.microseconds; // Subtle Timeunit.nanoseconds; // na-Sec
5, WorkQueue: A blocking queue, used to store the task waiting to be executed, the choice of this parameter is also very important, will have a significant impact on the running process of the thread pool,
In general, there are several options for blocking queues here:
Arrayblockingqueue; Linkedblockingqueue; Synchronousqueue;
Arrayblockingqueue and Priorityblockingqueue use less, generally using linkedblockingqueue and synchronous.
The thread pool's queuing policy is related to Blockingqueue.
6, Threadfactory: Thread factory, mainly used to create threads;
7. Handler: Indicates the following four kinds of values when the policy is rejected when processing a task:
Reference post: http://www.cnblogs.com/dolphin0520/p/3932921.html
Java Multithreading Summary