• 走近Callable


    1.特点

    1. 可以有返回值
    2. 可以抛出异常
    3. 方法不同, run() / call();

    Callable 接口类似于Runnable ,因为它们都是为其实例可能有另一个线程执行的类设计的,

    然而,Runnable不返回结果,也不能抛出被检查的异常。

    2.代码测试

    1. package com.kuang.callable;
    2. import java.util.concurrent.Callable;
    3. import java.util.concurrent.ExecutionException;
    4. import java.util.concurrent.FutureTask;
    5. import java.util.concurrent.TimeUnit;
    6. public class CallableTest {
    7. public static void main(String[] args) throws ExecutionException, InterruptedException {
    8. // new Thread(new Thread(new Runnable())).start(); 现在尽量少用
    9. // new Thread(new FutureTask()).start();
    10. // new Thread(new FutureTask(Callable())).start();
    11. //怎么启动Callable
    12. MyThread myThread = new MyThread();
    13. FutureTask futureTask = new FutureTask(myThread);//适配类
    14. new Thread(futureTask,"A").start();
    15. //会被阻塞直到它callable线程结束才会走这个方法
    16. String res = (String) futureTask.get();//获取返回值
    17. System.out.println(res);
    18. }
    19. }
    20. class MyThread implements Callable {
    21. //泛型的类型 等于 call() 方法返回值的类型
    22. @Override
    23. public String call() throws Exception {
    24. System.out.println("began");
    25. TimeUnit.SECONDS.sleep(10);
    26. System.out.println(Thread.currentThread().getName());
    27. return "2131sadad";
    28. }
    29. }

    源码返回  FutureTask的run方法

    1. public void run() {
    2. if (state != NEW ||
    3. !UNSAFE.compareAndSwapObject(this, runnerOffset,
    4. null, Thread.currentThread()))
    5. return;
    6. try {
    7. Callable c = callable;
    8. if (c != null && state == NEW) {
    9. V result;
    10. boolean ran;
    11. try {
    12. result = c.call();
    13. ran = true;
    14. } catch (Throwable ex) {
    15. result = null;
    16. ran = false;
    17. setException(ex);
    18. }
    19. if (ran)
    20. set(result);
    21. }
    22. } finally {
    23. // runner must be non-null until state is settled to
    24. // prevent concurrent calls to run()
    25. runner = null;
    26. // state must be re-read after nulling runner to prevent
    27. // leaked interrupts
    28. int s = state;
    29. if (s >= INTERRUPTING)
    30. handlePossibleCancellationInterrupt(s);
    31. }
    32. }

  • 相关阅读:
    数据结构和算法(15):排序
    六月集训(23)字典树
    牛客练习赛106
    电子巡更和智能巡检关系
    计算机视觉40例案例介绍
    Docker 容器文件(数据)共享
    SQL注入实例(sqli-labs/less-9)
    在.NET 6.0中自定义接口路由
    MP、MybatisPlus、联表查询、自定义sql、Constants.WRAPPER、ew (二)
    kettle从入门到精通 第七十课 ETL之kettle kettle数据校验,脏数据清洗轻松拿捏
  • 原文地址:https://blog.csdn.net/qq_53374893/article/details/132939356