实现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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在中,可以通过实现Callable接口来创建一个带返回值的线程任务。与Runnable接口不同,Callable接口的call()方法可以返回一个结果,而且可以抛出异常。 下面是一个简单的例子: ```java import java.util.concurrent.Callable; public class MyCallable implements Callable<String> { public String call() throws Exception { // 在这里编写你的多线程代码 return "Hello World"; } } ``` 在上面的代码中,我们实现Callable接口,并且重写了call()方法。在这个方法中,我们可以编写我们的多线程代码,并且使用return语句返回一个结果。 然后,我们可以在主线程中使用Callable创建一个Future对象,以便在后面获取线程的结果。下面是一个使用Future的例子: ```java import java.util.concurrent.*; public class Main { public static void main(String[] args) throws Exception { // 创建一个ExecutorService,用于执行Callable任务 ExecutorService executor = Executors.newSingleThreadExecutor(); // 创建一个Callable任务 Callable<String> callable = new MyCallable(); // 提交任务并返回一个Future对象 Future<String> future = executor.submit(callable); // 等待任务执行完成并获取结果 String result = future.get(); // 输出结果 System.out.println(result); // 关闭ExecutorService executor.shutdown(); } } ``` 在上面的代码中,我们首先创建了一个ExecutorService,它用于执行Callable任务。然后,我们创建了一个Callable任务,并将其提交给ExecutorService。这个方法返回一个Future对象,我们可以使用它来等待任务执行完成并获取结果。最后,我们输出结果,并关闭ExecutorService。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值