走近Callable

1.特点

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

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

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

2.代码测试

package com.kuang.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class CallableTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

//        new Thread(new Thread(new Runnable())).start(); 现在尽量少用
//        new Thread(new FutureTask<V>()).start();
//        new Thread(new FutureTask<V>(Callable())).start();
      //怎么启动Callable
        MyThread myThread = new MyThread();
        FutureTask futureTask = new FutureTask(myThread);//适配类
        new Thread(futureTask,"A").start();

        //会被阻塞直到它callable线程结束才会走这个方法
        String res = (String) futureTask.get();//获取返回值
        System.out.println(res);


    }


}


class  MyThread implements Callable<String> {
//泛型的类型 等于 call() 方法返回值的类型

    @Override
    public String call() throws Exception {
        System.out.println("began");
        TimeUnit.SECONDS.sleep(10);
        System.out.println(Thread.currentThread().getName());
        return "2131sadad";
    }
}

源码返回  FutureTask的run方法

public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值