1 import java.text.SimpleDateFormat;
2 import java.util.Date;
3 import java.util.concurrent.Callable;
4 import java.util.concurrent.ExecutionException;
5 import java.util.concurrent.FutureTask;
6 import java.util.concurrent.TimeUnit;
7
8 /**
9 * 线程类的几种方式
10 * 1、extends Thread
11 * 2、impleements Runnable
12 * 3、implements Callable<Integer>
13 * 总结出Runnable和Callable的区别
14 */
15 class MyThread2 implements Runnable{
16
17 @Override
18 public void run() {
19
20 }
21 }
22 class MyThread implements Callable<Integer>{
23
24 @Override
25 public Integer call() throws Exception {
26 System.out.println("coming in call "+Thread.currentThread().getName());
27 TimeUnit.SECONDS.sleep(2);
28 return 1024;
29 }
30 }
31
32 /**
33 * 编程思想,传参传接口,
34 * Runnable->FutureTask(Callable)
35 * Thread(Runnable,Name)
36 */
37 public class CallableDemo {
38 public static void main(String[] args) throws ExecutionException, InterruptedException {
39 System.out.println(Thread.currentThread().getName()+"主线程运行于此"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
40 MyThread thread=new MyThread();
41 FutureTask task=new FutureTask(thread);
42 Thread t=new Thread(task,"AA");
43 //Thread t2=new Thread(task,"BB");t2.start();无效,不可再次运行同样的结果,因重复利用t的结果,如需再次进入,创建FutureTask
44 t.start();
45 //对于get值,一般我们留出尽可能多的时间给线程进行运算,避免因为线程运算get()等待线程完成出现的阻塞
46 // int result = (Integer)task.get();
47 int num=100;
48 System.out.println(Thread.currentThread().getName()+"主线程运行于此"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
49 int result = (Integer)task.get();
50 System.out.println(Thread.currentThread().getName()+"\t 计算的总结果为"+(num+result));
51 }
52 }