Java 1.5, the JDK added a package concurrent, for our multi-thread program writing has brought great convenience. This is mainly to the previous use of multi-threaded knowledge comb.
The first class that needs to be used is java.util.concurrent.Executors, which generates the thread executor Java.util.concurrent.ExecutorService, and can then run the thread in different ways as needed, such as: a single task can be either executorservice.submit (Task) or execute (Task), which is a executorservice interface, which can return a value after the task has been executed, which is not a return value. Of course, the difference between the two is quite large, the former will certainly be runnable task packaging into Futuretask, the latter is not necessarily. Multiple tasks can be executed with invokeall/invokeany submission.
Executorservice es = executors.newsinglethreadexecutor (); future <String> r = Es.submit (new Task ()); Es.shutdown (); Try { r.get (); // Get result Catch (interruptedexception e) { //catch (executionexception e) { //}
A bit more detailed code:
Public classMyThreadextendsThread { PublicMyThread (String string) {Super(string); Super. SetName (String); } @Override Public voidrun () {System.out.println ( This. GetName () + "Start execution ... "); Try{sleep (101); System.out.println ( This. GetName () + "Execution End"); } Catch(interruptedexception e) {e.printstacktrace (); } }}
Public Static voidMain (string[] args)throwsinterruptedexception, executionexception{executorservice signalthread=Executors.newsinglethreadexecutor (); MyThread ThreadTest=NewMyThread ("First Test1"); MyThread ThreadTest2=NewMyThread ("First Test2"); Signalthread.execute (ThreadTest); Future<?> result =Signalthread.submit (THREADTEST2); Signalthread.shutdown (); Thread.Sleep (500); if(Result.isdone ()) {System.out.println (Result.get ()); } if(!threadtest2.isalive ()) {System.out.println (Result.get ()); } }
Results:
first test1 starts executing ... First test1 execution end test2 start execution ... First test2 execution end nullnull
Java.util.concurrent.Executors This class is like manipulating an array of classes arrays, looking at the description of the class, primarily providing Java concurrent package Executor ,, ExecutorService , ScheduledExecutorService , ThreadFactory and Callable class的工厂和实用方法。阅读其代码也不多,
发现他创建线程执行器大致分为两种,一种是ThreadPoolExecutor,另一种ThreadPoolExecutor/ScheduledThreadPoolExecutor包装以后的线程执行器;
创建Callable主要有两种,一是将Runnable适配一下返回RunnableAdapter,另一是包装了Callable的PrivilegedCallable;创建ThreadFactory也主要是两种,都是其内部类,一是DefaultThreadFactory,另一是PrivilegedThreadFactory;总之,他可以看作工厂方法类,其他创建的ThreadFactory、Callable可以先放放。
Executors创建的ExecutorService了。产看该接口,该接口集成自父接口:Executor。Executor接口只定义了void execute(Runnable command)方法,用来执行提交的任务。而ExecutorService除了execute方法之外,还定义了submit,invorkAll,invokeAny,shutdwon等等方法,主要用来执行并跟踪多个异步任务,终止管理等。AbstractExecutorService类提供了ExecutorService接口除了execute之外其他方法的默认实现。产看其代码,发现真正执行任务的却是他没有实现的execute方法,其他执行线程的方法,如sumbit和invokeAll内部都会调用execute(Runnable)方法,而invokeAny方法在其调用的doInvokeAny方法中还是会在ExecutorCompletionService.submit方法中调用execute(Runnable)方法。
具体代码就不贴了,JDK中都有。这里顺便对submit,invokeAll,invokeAny方法的区别不提了,JDK方法都有注释,比较简单。
<T> Future<T> submit(Callable<T> task)
A task that submits a return value is used to execute, returning a future that represents the pending result of the task.
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
Executes the given task, returning a list of future tasks that hold the status and results of the task when all tasks are completed.
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
Executes the given task, and returns the result if a task has completed successfully (that is, an exception is thrown).
要提下,执行的任务。从void execute(Runnable command)的签名可以看出他执行的任务是Runnable,众所周知Runnable任务是没有返回值的,若需要任务的返回值则需要Callable来作为任务,
这里Concurrent提供了Runnable和Callable的适配器。invokeAll,submit,invokeAny方法中会将Runnable包装成callable来执行。具体:
Reference: http://songzi0206.iteye.com/blog/1207349
Multithreading (i)