java multithreading Callable interface and its q difference Runnable

Callable interface, and the interface is similar to Runnable, Callable difference is the need to implement the method call, and the need to implement Runnable run method; and, call method can also return any object , no matter what the object, JVM will be managed as Object to deal with. But if you use generics, we do not always have to convert the Object.

 

Runnable and Callable interfaces are

differences:
1. Callable can return a type V, and not Runnable
2. Callable can throw checked exception, and can not Runnable .
Since there is 3.Runnable java1.1, and Callable was only added to the list after 1.5
4. Callable and Runnable can be applied to executors. The Thread class only supports Runnable .
Above simply different, in fact, these two interfaces using up the difference is great. Callable united with the executors, you can get an updated Future when the task is completed immediately. The Runable have to deal with their own

 

  Future interface, are generally performed by retrieving the state Callable. One of the main methods:

  • cancel, cancel Callable execution has not been completed when Callable
  • get, get Callable return value
  • isCanceled, to determine whether to cancel the
  • isDone, determined whether

 

Executor to build with thread pools should do:

1) Call the static method newCachedThreadPool Executors class (create a new thread if necessary, idle threads are retained 60 seconds) or newFixedThreadPool (containing a fixed number of thread pool), etc., is a return realized ThreadPoolExecutor class ExecutorService interface or is a class that implements the object ScheduledExecutorServiece interface.

2) Calling submit submit Runnable or Callable object.

3) If you want to cancel a job, or if you submit a Callable object, it would be good to save Future object returned.

4). When no longer submit any task, call the shutdown method .

————————————————————————————

Abstract content in https://www.iteye.com/blog/uule-1488270

Guess you like

Origin www.cnblogs.com/lingchendujing/p/11492183.html