zoukankan      html  css  js  c++  java
  • 6. Callable

    @FunctionalInterface (函数式接口)
    public interface Callable返回结果并可能引发异常的任务。 实现者定义一个没有参数的单一方法,称为call 。

    Callable接口类似于Runnable ,因为它们都是为其实例可能由另一个线程执行的类设计的。 然而,A Runnable不返回结果,也不能抛出被检查的异常。

    该Executors类包含的实用方法,从其他普通形式转换为Callable类。

    1. Callable 有返回值
    2. 可以抛出异常
    3. 方法不同。call()

    代码测试

    Thread 运行 Callable 线程

    package pers.vincent.matrix.subject.callable;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
    
    public class CallableTest {
    
        public static void main(String[] args) throws ExecutionException, InterruptedException {
    
            MyThread2 myThread2 = new MyThread2();
            // A FutureTask可用于包装Callable或Runnable对象。 因为FutureTask实现Runnable ,一个FutureTask可以提交到一个Executor执行。
            Callable callable;
            FutureTask futureTask = new FutureTask<>(myThread2);
    
            new Thread(futureTask).start();
    
            String str = (String) futureTask.get();
            System.out.println(str);
        }
    
    }
    
    // 旧的多线程实现方法
    class MyThread implements Runnable{
    
        @Override
        public void run() {
    
        }
    }
    
    // callable
    class MyThread2 implements Callable<String>{
    
        @Override
        public String call() throws Exception {
            System.out.println("AAAAA");
            return "123";
        }
    }
    
  • 相关阅读:
    转载-WebSocket协议解析
    django sqlite3数据迁入postgresql
    使用JenKins实现自动执行python脚本
    调用函数的局部变量
    打开新窗口获取元素
    邮箱登录脚本
    购物车小程序
    循环
    格式化的输出
    使用#号输出图形,可以指定宽和高
  • 原文地址:https://www.cnblogs.com/blackBlog/p/13451433.html
Copyright © 2011-2022 走看看