Runnable和Callable的区别

了解一下

在java中线程类是java.lang.Thread,看源码可知线程类是实现了java.lang.Runnable接口的。我们如果想运行一个线程,可以新建一个java.lang.Thread并重写run()方法去执行自己的任务,当然也可以向java.lang.Thread对象中填入一个实现了java.lang.Runnable接口的类。

java.util.concurrent.Callable接口是什么?定义了返回结果的任务接口,和java.lang.Runnable 相似,但是其使用还是要依赖java.lang.Runnable,为什么这么说呢,请往下看。

Callable的使用

在java中,Callable的最先是在线程池中使用的。

	public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);  //封装Callable为FutureTask
        execute(ftask); //运行FutureTask
        return ftask; //返回FutureTask
    }

FutureTask

在这里插入图片描述

  • Future接口
    取消任务
    获取任务结果(检查计算是否为完成,等待其完成再返回结果,一旦完成,无法取消)
  • RunnableFuture继承了Runnable和Future
  • FutureTask是RunnableFuture的实现类,也就是实现了Runnable和Future的功能

FutureTask功能: 启动,取消,查询是否完成检索计算结果,如果计算未完成,方法将阻塞,一旦计算完成,无法重新计算或取消除非调用runAndReset()

状态

在这里插入图片描述
状态变化:
在这里插入图片描述

方法

  1. 构造方法:
	public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
	public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result); //通过Runnable封装为RunnableAdapter,而RunnableAdapter实现了Callable
        this.state = NEW;  
    }
  1. 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(); //获取call的结果
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);//将call的结果存储起来
            }
        } 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. get方法
	public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L); //如果没有完成,等待结果返回
        return report(s);
    }
  1. awaitDone方法
    等待结果,中断终止,超时
	private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        for (;;) {
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            else if (q == null)
                q = new WaitNode();
            else if (!queued)
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            else if (timed) {
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                LockSupport.parkNanos(this, nanos);
            }
            else
                LockSupport.park(this);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

code_wang_hui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值