Callable 接口类似于Runnable ,因为它们都是为其实例可能有另一个线程执行的类设计的,
然而,Runnable不返回结果,也不能抛出被检查的异常。

- package com.kuang.callable;
-
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.FutureTask;
- import java.util.concurrent.TimeUnit;
-
- public class CallableTest {
-
- public static void main(String[] args) throws ExecutionException, InterruptedException {
-
- // new Thread(new Thread(new Runnable())).start(); 现在尽量少用
- // new Thread(new FutureTask
()).start(); - // new Thread(new FutureTask
(Callable())).start(); - //怎么启动Callable
- MyThread myThread = new MyThread();
- FutureTask futureTask = new FutureTask(myThread);//适配类
- new Thread(futureTask,"A").start();
-
- //会被阻塞直到它callable线程结束才会走这个方法
- String res = (String) futureTask.get();//获取返回值
- System.out.println(res);
-
-
- }
-
-
- }
-
-
- class MyThread implements Callable
{ - //泛型的类型 等于 call() 方法返回值的类型
-
- @Override
- public String call() throws Exception {
- System.out.println("began");
- TimeUnit.SECONDS.sleep(10);
- System.out.println(Thread.currentThread().getName());
- return "2131sadad";
- }
- }
- public void run() {
- if (state != NEW ||
- !UNSAFE.compareAndSwapObject(this, runnerOffset,
- null, Thread.currentThread()))
- return;
- try {
- Callable
c = callable; - if (c != null && state == NEW) {
- V result;
- boolean ran;
- try {
- result = c.call();
- ran = true;
- } catch (Throwable ex) {
- result = null;
- ran = false;
- setException(ex);
- }
- if (ran)
- set(result);
- }
- } finally {
- // runner must be non-null until state is settled to
- // prevent concurrent calls to run()
- runner = null;
- // state must be re-read after nulling runner to prevent
- // leaked interrupts
- int s = state;
- if (s >= INTERRUPTING)
- handlePossibleCancellationInterrupt(s);
- }
- }