Talk about Runnable and Callable

Callable interface:

1 public interface Callable<V> {
2     V call() throws Exception;
3 }

Runnable interface:

public interface Runnable {
    public abstract void run();
}

Same point:

  1. Both are interfaces; (nonsense)
  2. Both can be used to write multithreaded programs;
  3. Both need to call Thread.start() to start the thread;

 

difference:

  1. The biggest difference between the two is that the task thread that implements the Callable interface can return the execution result; the task thread that implements the Runnable interface cannot return the result;
  2. The call() method of the Callable interface allows exceptions to be thrown; while the exceptions of the run() method of the Runnable interface can only be digested internally, and cannot continue to be thrown;

 

important point:

  • The Callable interface supports returning the execution result. In this case, the FutureTask.get() method needs to be called. This method will block the main thread until the 'future' result is obtained; when this method is not called, the main thread will not block!

 

Demo of Callable working:

 1 package com.callable.runnable;
 2 
 3 import java.util.concurrent.Callable;
 4 import java.util.concurrent.ExecutionException;
 5 import java.util.concurrent.FutureTask;
 6 
 7 /**
 8  * Created on 2016/5/18.
 9  */
10 public class CallableImpl implements Callable<String> {
11 
12     public CallableImpl(String acceptStr) {
13         this.acceptStr = acceptStr;
14     }
15 
16     private String acceptStr;
17 
18     @Override
19     public String call() throws Exception {
20         // 任务阻塞 1 秒
21         Thread.sleep(1000);
22         return this.acceptStr + " append some chars and return it!";
23     }
24 
25 
26     public static void main(String[] args) throws ExecutionException, InterruptedException {
27         Callable<String> callable = new CallableImpl("my callable test!");
28          FutureTask<String> task = new FutureTask<> (callable);
 29          long beginTime = System.currentTimeMillis();
 30          // Create a thread 
31          new Thread(task).start();
 32          // Call get() to block the main 
33          String result = task.get ();
 34          long endTime = System.currentTimeMillis();
 35          System.out.println("hello : " + result);
 36          System.out.println( "cast : " + (endTime - beginTime) / 1000 + " second!" );
 37      }
 38}

Test Results:

hello : my callable test! append some chars and return it!
cast : 1 second!

Process finished with exit code 0

 

Demo of Runnable working:

 1 package com.callable.runnable;
 2 
 3 /**
 4  * Created on 2016/5/18.
 5  */
 6 public class RunnableImpl implements Runnable {
 7 
 8     public RunnableImpl(String acceptStr) {
 9         this.acceptStr = acceptStr;
10     }
11 
12     private String acceptStr;
13 
14     @Override
15     public void run() {
16         try {
17             //The thread is blocked for 1 second, and an exception occurs at this time, which can only be digested inside the method, and cannot be thrown up 
18              Thread.sleep(1000 );
 19          } catch (InterruptedException e) {
 20              e.printStackTrace();
 21          }
 22          // Finally The processing result cannot be returned 
23          System.out.println("hello : " + this .acceptStr);
 24      }
 25  
26  
27      public  static  void main(String[] args) {
 28          Runnable runnable = new RunnableImpl("my runable test!" );
 29          long beginTime = System.currentTimeMillis();
30         new Thread(runnable).start();
31         long endTime = System.currentTimeMillis();
32         System.out.println("cast : " + (endTime - beginTime) / 1000 + " second!");
33     }
34 }

Test Results:

cast : 0 second!
hello : my runable test!

Process finished with exit code 0

The reason for writing this article is that the difference between Callable and Runnable was asked in an interview. At that time, Runnable was used more, while Callable was rarely used!

After comparing the two (checked a lot on the Internet), I found that Callable is still very useful in many special scenarios! Finally, leave some copied code to deepen your understanding of Callable!

 1 package com.inte.fork;
 2 
 3 /**
 4  * Created on 2016/4/20.
 5  */
 6 
 7 import java.util.*;
 8 import java.util.concurrent.*;
 9 
10 import static java.util.Arrays.asList;
11 
12 public class Sums {
13 
14     static class Sum implements Callable<Long> {
15         private final long from;
16         private final long to;
17 
18         Sum(long from, long to) {
19             this.from = from;
20             this.to = to;
21         }
22 
23         @Override
24         public Long call() {
25             long acc = 0;
26             for (long i = from; i <= to; i++) {
27                 acc = acc + i;
28             }
29             System.out.println(Thread.currentThread().getName() + " : " + acc);
30             return acc;
31         }
32     }
33 
34     public static void main(String[] args) throws Exception {
35         ExecutorService executor = Executors.newFixedThreadPool(3);
36         List<Future<Long>> results = executor.invokeAll(asList(
37                 new Sum(0, 10), new Sum(0, 1_000), new Sum(0, 1_000_000)
38         ));
39         executor.shutdown();
40 
41         for (Future<Long> result : results) {
42             System.out.println(result.get());
43         }
44     }
45 }

 

 

This article is reprinted from: https://www.cnblogs.com/frider6/p/5507082.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324979791&siteId=291194637