• 关于线程3


    线程定义和创建3:实现Callable接口

    JDK1.5后推出了第三种定义线程的方式,实现Callable接口

    public class RandomCallable implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            Thread.sleep(5000);
            //throw new IOException();
            return new Random().nextInt(10);
        }
        public static void main(String[] args)
                throws InterruptedException, ExecutionException {
            //创建线程对象
            Callable<Integer> callable = new RandomCallable();
            FutureTask<Integer> task = new FutureTask<Integer>(callable);
            Thread thread = new Thread(task);
            //启动线程
            thread.start();
            //获取返回值
            System.out.println(task.isDone());

    //必须等线程执行完毕后,才能得到返回值,线程在此会阻塞
            Integer num = task.get();
            System.out.println(num);
            System.out.println(task.isDone());//线程是否执行完毕
        }
    }

    第三种方式:实现Callable接口

    与实行Runnable相比, Callable功能更强大些

    • 方法名不同  
    • 可以有返回值,支持泛型的返回值
    • 可以抛出检查异常
    • 需要借助FutureTask,比如获取返回结果 

    Future接口

    • 可以对具体Runnable、Callable任务的执行结果进行取消、查询是否完成、获取结果等。
    • FutrueTask是Futrue接口的唯一的实现类
    • FutureTask 同时实现了Runnable, Future接口。它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值 
  • 相关阅读:
    python使用thrift访问操作hbase
    js打开新页面
    设计模式
    c# dotfuscator 混淆后无法使用
    SQL server清空数据库日志脚本
    SQlserver 行转列
    SQLServer 脚本测试
    C# HttpWebRequest与HttpWebResponse详解
    反射
    SQl server master
  • 原文地址:https://www.cnblogs.com/vincentmax/p/14246022.html
Copyright © 2020-2023  润新知