您好,欢迎来到华佗小知识。
搜索
您的当前位置:首页实现Callable接口实现多线程

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

 

转载于:https://www.cnblogs.com/sunnyDream/p/7997400.html

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务