自Java 5开始,java提供Callable接口,它提供call()方法作为线程执行体,但比run()方法更强大

  • call()方法可以有返回值

  • call()方法可以声明抛出异常

因此,现在可以提供一个Callable对象作为Thread的target。

同时,Java 5提供Future接口代表Callable接口call()方法的返回值,并为其提供FutureTask实现类。

Future接口定义几个公共方法用来控制它关联的Callable任务:

  • boolean cancel(boolean mayInterruptIRunning):试图取消Future关联的Callable任务

  • V get():获取call()的返回值,调用该方法将导致阻塞,必须等到子线程结束

  • V get(long timeout,TimeUnit unit):返回call()方法的返回值,指定最多阻塞时间,否则抛出异常

  • boolean isCancelled():如果在callable任务正常完成前被取消,则返回true

  • boolean isDone():如果callable任务已完成,则返回true

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class Test03 implements Callable<Integer> {

    public static void main(String[] args) {
        Test03 rt=new Test03();
        FutureTask<Integer> task=new FutureTask<Integer>(rt);
        for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName()+" "+i);
            if(i==20){
                new Thread(task,"返回值的线程").start();
            }
        }
        try{
            System.out.println("子线程的返回值: "+task.get());
        }catch(Exception ex){
            ex.printStackTrace();
        }

    }

    @Override
    public Integer call() throws Exception {
        int i=0;
        for(;i<100;i++){
            System.out.println(Thread.currentThread().getName()+" "+i);
        }
        return i;
    }

}

results matching ""

    No results matching ""