future异步回调

Callable接口类似于Runnable,从名字就可以看出来了,但是Runnable不会返回结果,并且无法抛出返回结果的异常,而Callable功能更强大一些,被线程执行后,可以返回值,这个返回值可以被Future拿到。FutureTask实现了两个接口,Runnable和Future,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值,那么这个组合的使用有什么好处呢?假设有一个很耗时的返回值需要计算,并且这个返回值不是立刻需要的话,那么就可以使用这个组合,用另一个线程去计算返回值,而当前线程在使用这个返回值之前可以做其它的操作,等到需要这个返回值时,再通过Future得到。

package asycall;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class CallableFuture {

    /** 
     * @param args 
     * @throws Exception 
     * @throws InterruptedException 
     */  
    public static void main(String[] args) throws InterruptedException,  
            Exception {  
        // TODO Auto-generated method stub  
        ExecutorService exec = Executors.newCachedThreadPool();  
        // Future是一个接口,该接口用来返回异步的结果。  
        Future<String> st = exec.submit(new TaskCallable());  

        System.out.println("-------------");
        /* 同步结果,并且设置超时时间 */  
        System.out.println(st.get(10000, TimeUnit.MILLISECONDS));  
        System.out.println("finished");  

    }  
}

callable

package asycall;

import java.util.concurrent.Callable;

public class TaskCallable implements Callable<String> {  

    public String call() throws Exception {  
        // TODO Auto-generated method stub  
        Thread.sleep(10000);  
        return "callstatus=OK";  
    }  

} 

得到的结果:

————-10秒后出现下面这一行。
callstatus=OK
finished
“`

这就符合客户端发送了数据之后,打印了———-,但是10s之后,才收到服务端发回来的callstatus=ok.

猜你喜欢

转载自blog.csdn.net/weixin_38070406/article/details/80773608