Callable使用

实现Callable接口的任务线程能返回执行结果,Callable接口的call()方法允许抛出异常。

注意点:

  • Callable接口支持返回执行结果,此时需要调用FutureTask.get()方法实现,此方法会阻塞主线程直到获取‘将来’结果;当不调用此方法时,主线程不会阻塞!
package com.java.my.callable;

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

/**
 * @author wanjiadong
 * @description
 * @date Create in 17:16 2018/2/1
 */
public class CallableImpl implements Callable {

    private String str;

    public CallableImpl(String str){
        this.str = str;
    }

    @Override
    public String call() throws Exception {
        Thread.sleep(1000);

        return "call:"+str;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableImpl callable = new CallableImpl("hello world!");
        FutureTask task = new FutureTask(callable);

        long beginTime = System.currentTimeMillis();
        new Thread(task).start();

        String result = task.get();
        System.out.println("task result = "+result);
        System.out.println("use time="+(System.currentTimeMillis()-beginTime));
    }
}


你可能感兴趣的:(callable,callable)