Three methods of multithreading: inheritance Thread class, implement Runnable and Callable interfaces to achieve

Three methods to achieve multi-threading:

1, inheritance Thread, override the run () method, call the start () method to start a thread;

2, implement Runnable, implement run () method, with a corresponding thread start new Thread (Runnable target) .start () method;

3, implement Callable interface using FutureTask wrapper implement call () method, and call () method returns a value, you can throw an exception;

1 //实现Callable接口
2 class Test implements Callable<Integer> {
3 
4     @Override
5     public Integer call() throws Exception {
6         return 1024;
7     }
8 }

Difference Callable interface Runnable interface:

(1) whether there is a return value

(2) whether Throws

(3) A method to achieve not the same, a RUN is, when a call method

 

Multi-threaded implementation implement Callable interface:

 1 import java.util.concurrent.Callable;
 2 import java.util.concurrent.ExecutionException;
 3 import java.util.concurrent.FutureTask;
 4 
 5 public class ThreadPro {
 6     public static void main(String[] args) throws ExecutionException, InterruptedException {
 7         Test test=new Test();
 8         FutureTask futureTask=new FutureTask(test);
 9         new Thread(futureTask,"A线程").start();
10         System.out.println("......");
11         System.out.println(futureTask.get());
12     }
13 }
14 
15 //实现Callable接口
16 class Test implements Callable<Integer> {
17 
18     @Override
19     public Integer call() throws Exception {
20         System.out.println("HELLO!......");
21         return 1024;
22     }
23 }

 

Thread class Callable no constructor directly into the interface, requires the use of implements Runnable interface, comprising packaging futureTask Callable Interface class constructor.

 

 引入Callable接口具有哪些好处:
(1),可以获得任务执行返回值;
(2),通过与FutureTest的结合,可以实现利用FutureTest来跟踪异步计算的结果。并且多个线程执行同一个类的call方法,只会被执行一次,因为返回值已经保存记住了。

 

Guess you like

Origin www.cnblogs.com/fangtingfei/p/12020772.html