author : Haizi

The articles not reprinted in this blog belong to the author Haizi And blog park , Welcome to reprint , However, this statement must be retained without the consent of the author , And in the article page obvious position gives the original link , Otherwise, the right to pursue legal responsibility is reserved .

Java Concurrent programming :Callable、Future and FutureTask

In the previous article, we talked about creating threads 2 Ways of planting , One is direct inheritance Thread, The other is to realize Runnable Interface .

this 2 There is a flaw in all of these ways : Unable to get execution result after task execution .

If you need to get execution results , You have to share variables or use thread communication to achieve the effect , In this way, it is more troublesome to use .

And since Java 1.5 Start , Provided. Callable and Future, Through them, you can get the task execution result after the task execution .

Let's talk about it today Callable、Future and FutureTask How to use the three classes . Here is the outline of this article :

One .Callable And Runnable

Two .Future

3、 ... and .FutureTask

Four . Examples of use

If there is anything wrong, please forgive me , And welcome criticism and correction .

Please respect the author's work , Please mark the link of the original text :

http://www.cnblogs.com/dolphin0520/p/3949310.html

One .Callable And Runnable

But first, let me say java.lang.Runnable Well , It's an interface , There is only one statement in it run() Method :

1
2
3
public  interface  Runnable {
     public  abstract  void  run();
}

because run() The return value of the method is void type , So you can't return any results after you finish the task .

Callable be located java.util.concurrent It's a bag , It's also an interface , Only one method is declared in it , It's just that this method is called call():

1
2
3
4
5
6
7
8
9
public  interface  Callable<V> {
     /**
      * Computes a result, or throws an exception if unable to do so.
      *
      * @return computed result
      * @throws Exception if unable to compute a result
      */
     V call()  throws  Exception;
}

You can see , This is a generic interface ,call() The type returned by the function is passed in V type .

So how to use Callable Well ? Usually it's a fit ExecutorService To use the , stay ExecutorService Several... Are declared in the interface submit Overloaded version of method :

1
2
3
<T> Future<T> submit(Callable<T> task);
<T> Future<T> submit(Runnable task, T result);
Future<?> submit(Runnable task);

first submit The parameter type in the method is Callable.

Just need to know for a while Callable Generally and ExecutorService Used in conjunction with , The specific usage will be described later .

Generally, we use the first submit Method and third submit Method , the second submit Methods are rarely used .

Two .Future

Future It's about the concrete Runnable perhaps Callable The execution result of the task is cancelled 、 Query complete 、 To get the results . Yes, if necessary get Method to get the execution result , This method blocks until the task returns a result .

Future Class is located java.util.concurrent It's a bag , It's an interface :

1
2
3
4
5
6
7
8
public  interface  Future<V> {
     boolean  cancel( boolean  mayInterruptIfRunning);
     boolean  isCancelled();
     boolean  isDone();
     V get()  throws  InterruptedException, ExecutionException;
     V get( long  timeout, TimeUnit unit)
         throws  InterruptedException, ExecutionException, TimeoutException;
}

stay Future The interface declares 5 A way , Next, explain the function of each method in turn :

  • cancel Method to cancel a task , Returns if the cancel task succeeds true, Returns if the cancel task fails false. Parameters mayInterruptIfRunning Indicates whether it is allowed to cancel a task that is being executed but not completed , If you set true, Means you can cancel a task while it is executing . If the task has been completed , No matter mayInterruptIfRunning by true still false, This method definitely returns false, That is, the completed task will be returned if cancelled false; If the task is being executed , if mayInterruptIfRunning Set to true, Then return to true, if mayInterruptIfRunning Set to false, Then return to false; If the task has not been executed , No matter mayInterruptIfRunning by true still false, Must be returned true.
  • isCancelled Method indicates whether the task was cancelled successfully , If the mission is cancelled before it is normally completed , Then return to true.
  • isDone Method indicates whether the task has been completed , If the task is completed , Then return to true;
  • get() Method to get the execution result , This method will block , Will wait until the task is completed to return ;
  • get(long timeout, TimeUnit unit) Used to get execution results , If within the specified time , We haven't got the result yet , Go straight back null.

in other words Future Three functions are provided :

1) Determine if the task is completed ;

2) Be able to interrupt tasks ;

3) Be able to get task execution results .

because Future It's just an interface , So it can't be used directly to create objects , So there's the following FutureTask.

3、 ... and .FutureTask

So let's see FutureTask The implementation of the :

1
public  class  FutureTask<V>  implements  RunnableFuture<V>

FutureTask Class implements the RunnableFuture Interface , Let's see RunnableFuture Interface implementation :

1
2
3
public  interface  RunnableFuture<V>  extends  Runnable, Future<V> {
     void  run();
}

It can be seen that RunnableFuture Inherited Runnable Interface and Future Interface , and FutureTask Realized RunnableFuture Interface . So it can be used as Runnable Executed by thread , Can be used as Future obtain Callable The return value of .

FutureTask Provides 2 Constructor :

1
2
3
4
public  FutureTask(Callable<V> callable) {
}
public  FutureTask(Runnable runnable, V result) {
}

in fact ,FutureTask yes Future A unique implementation class of the interface .

Four . Examples of use

1. Use Callable+Future Get execution results

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public  class  Test {
     public  static  void  main(String[] args) {
         ExecutorService executor = Executors.newCachedThreadPool();
         Task task =  new  Task();
         Future<Integer> result = executor.submit(task);
         executor.shutdown();
         
         try  {
             Thread.sleep( 1000 );
         catch  (InterruptedException e1) {
             e1.printStackTrace();
         }
         
         System.out.println( " The main thread is executing the task " );
         
         try  {
             System.out.println( "task Running results " +result.get());
         catch  (InterruptedException e) {
             e.printStackTrace();
         catch  (ExecutionException e) {
             e.printStackTrace();
         }
         
         System.out.println( " All tasks are completed " );
     }
}
class  Task  implements  Callable<Integer>{
     @Override
     public  Integer call()  throws  Exception {
         System.out.println( " The child thread is calculating " );
         Thread.sleep( 3000 );
         int  sum =  0 ;
         for ( int  i= 0 ;i< 100 ;i++)
             sum += i;
         return  sum;
     }
}

Execution results :

 The child thread is calculating 
The main thread is executing the task
task Running results 4950
All tasks are completed

2. Use Callable+FutureTask Get execution results

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public  class  Test {
     public  static  void  main(String[] args) {
         // The first way
         ExecutorService executor = Executors.newCachedThreadPool();
         Task task =  new  Task();
         FutureTask<Integer> futureTask =  new  FutureTask<Integer>(task);
         executor.submit(futureTask);
         executor.shutdown();
         
         // The second way , Notice that this is similar to the first way , It's just that one uses ExecutorService, One uses Thread
         /*Task task = new Task();
         FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
         Thread thread = new Thread(futureTask);
         thread.start();*/
         
         try  {
             Thread.sleep( 1000 );
         catch  (InterruptedException e1) {
             e1.printStackTrace();
         }
         
         System.out.println( " The main thread is executing the task " );
         
         try  {
             System.out.println( "task Running results " +futureTask.get());
         catch  (InterruptedException e) {
             e.printStackTrace();
         catch  (ExecutionException e) {
             e.printStackTrace();
         }
         
         System.out.println( " All tasks are completed " );
     }
}
class  Task  implements  Callable<Integer>{
     @Override
     public  Integer call()  throws  Exception {
         System.out.println( " The child thread is calculating " );
         Thread.sleep( 3000 );
         int  sum =  0 ;
         for ( int  i= 0 ;i< 100 ;i++)
             sum += i;
         return  sum;
     }
}

If used for cancellability Future But it does not provide usable results , Then you can declare Future<?> In the form of type 、 And back to null As a result of the underlying task .

 

Java Concurrent programming :Callable、Future and FutureTask More articles about

  1. Java Concurrent programming ——Callable+Future+FutureTask

    Java Concurrent programming series Java Concurrent basis —— Thread safety Java Concurrent programming ——Callable+Future+FutureTask java Concurrent programming ——Thread Relearn the source code java Concurrent ...

  2. java Concurrent runable,callable,future,futureTask

    Reprinted from :http://www.cnblogs.com/dolphin0520/p/3949310.html package future_call; import java.util.concurre ...

  3. 【 original 】JAVA Concurrent programming ——Callable and Future Source code exploration

    JAVA There are three main ways to implement multithreading : Inherit Thread class . Realization Runnable Interface . Use ExecutorService.Callable.Future Implement multiple threads that return results . In the first two ways, the thread is not executed ...

  4. java: Concurrent programming -Callable And Future Pattern

    My understanding of thread pool : coresize 3 maxsize 5 blockLinkedQuenue 3 When the submitted task is in <=3 when , Create three threads Greater than 3 when , Add the task to the blocking queue first , When there is a free core ...

  5. 【 Concurrent programming 】Future and FutureTask as well as CompletionService

    Future Interface This interface is mainly used for : Represents the execution result of asynchronous computation : For cancellable task:( Than using interrupt It should be convenient to cancel ) FutureTask class FutureTask yes Future An implementation class ...

  6. Java Concurrent programming :Callable and Future

    There are often tasks in a project that need to be asynchronous ( Commit to thread pool ) To carry out , The main thread often needs to know the result of asynchronous execution , Now what are we going to do ? use runnable It's impossible , We need to use callable Realization . import java ...

  7. Java Concurrent programming &mdash;&mdash;Executor Framework and thread pool principle

    Eexecutor As a flexible and powerful asynchronous execution framework , It supports many different types of task execution strategies , It provides a standard method to decouple the task submission process from the task execution process , Based on producer - Consumer model , The thread that submits the task is equivalent to the producer , Perform tasks ...

  8. java Concurrent programming —— adopt ReentrantLock,Condition Realize bank deposit and withdrawal

         java.util.concurrent.locks Packages provide a framework interface and class for lock and wait conditions , It's different from the built-in synchronization and monitor . The framework allows for more flexible use of locks and conditions , But at the cost of more difficult grammar . Lock Interface ...

  9. Java Concurrent programming ——BlockingQueue

    brief introduction BlockingQueue A good solution to multithreading , How to be efficient and safe " transmission " Data problems . Through these efficient and thread safe queue classes , It is very convenient for us to build high quality multithreaded programs . The blocking queue is ...

  10. java Concurrent programming ——Thread Relearn the source code

    Java Concurrent programming series Java Concurrent basis —— Thread safety Java Concurrent programming ——Callable+Future+FutureTask java Concurrent programming ——Thread Relearn the source code java Concurrent ...

Random recommendation

  1. Android The development case - Gallery

    This article does not cover UI Aspects of , If you want to know UI Visitors from all walks of life , Please skip this article . This article will introduce how to load the local library smoothly . It's used more than usual , Such as WeChat ( See the picture below ), Microblog and other applications , All of them have realized the library function , Its ...

  2. 64 How to import the bit system excel

    1. function C:\Windows\SysWOW64\odbcad32.exe, Open as shown in the following figure : 2. Click Add , Select... As shown in the figure below Microsoft Excel Driver(*.xls) 3. Click finish , Playing ...

  3. java arraylist The problem of

    Have to say , I made a mistake , Very basic .. Traverse list Can I delete an array element when I delete it ? The answer is : Simple / enhance for Circulation can't be ,list.iterator() This way, you can . I've done similar interview questions before , But I forgot , No ...

  4. Luogu P1896 Don't invade each other King

    P1896 [SCOI2005] Don't invade each other King Title Description stay N×N In my chessboard K A king , Keep them from attacking each other , How many layout plans are there . The king can attack it up, down, left and right , And a grid in the upper left, lower left, upper right and lower right directions , common ...

  5. android studio2.0 build Robotium Environmental Science -- With the source code under test

    1. Import robotium-solo-5.2.1.jar package     Import junit:4.12.jar2.app- -src- -main- -libs perhaps app-libs Next After copying in , Right click add a ...

  6. The purity of advanced chapter css+ Font realizes Pentagram ( Half a star ) score

    1. Preface   Before I wrote an article to achieve Pentagram scoring effect demo. This demo It's more than enough to achieve the scoring effect , Well, sometimes when we're counting scores , There will be half a star or 1/3 How can a star like this be realized ? Come on, come on , Plain font +css Realization ! ...

  7. virtual machine console Infrastructure deployment —— Configure local YUM Source

    1. CD/ROM Mount the system image 2. Mount device 3. Configure local source 4. summary of YUM Source and Linux Three software management modes of the system , Reference blog <CentOS There are three software management systems >, Notes inside the chain :CentOS System three ...

  8. Double.valueOf(0.0D) analysis

    private Double price = Double.valueOf(0.0D); see Java API The documents are as follows : doubleValue public double doubleValue( ...

  9. iOS Random number acquisition

    // Get one 32 Bit random number static const char _randomStr[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv ...

  10. x264_param_default analysis

    {     /* Open up memory space */     memset( param, 0, sizeof( x264_param_t ) );              /* CPU Automatic detection */     par ...