实现Callable接口实现多线程

package com.roocon.thread.t2;

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

public class Demo4 implements Callable<Integer>{

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Demo4 d = new Demo4();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(d); //将线程任务封装成futureTask对象
        Thread thread = new Thread(futureTask); //与runnable类似,将封装好的futureTask对象作为参数传入Thread类,这样最终会调用futureTask中定义的任务。
thread.start(); Integer result = futureTask.get(); System.out.println("执行结果为"+result); } @Override public Integer call() throws Exception { System.out.println("正在进行紧张的计算"); Thread.sleep(1000); return 4; } }

运行结果:

正在进行紧张的计算
执行结果为4

 

源码解读:

FutureTask实现了RunnableFuture接口,RunnableFuture接口又继承了Runnable接口。这样,最终会调用它定义好的run方法。
public class FutureTask<V> implements RunnableFuture<V> {
    ...
}

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

 

posted @ 2017-12-07 07:36  凌晨六点半  阅读(588)  评论(0编辑  收藏  举报