实现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();
}

作者:凌晨六点半
出处:http://www.cnblogs.com/sunnyDream/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。 如果您认为这篇文章还不错或者有所收获,您可以通过右边的“打赏”功能 打赏我一杯咖啡【物质支持】,也可以点击右下角的【好文要顶】按钮【精神支持】,因为这两种支持都是我继续写作,分享的最大动力!

原文地址:https://www.cnblogs.com/sunnyDream/p/7997400.html