Callable

面试中或许都遇到过这样的问题:“Java中创建线程的方式有哪些?”,本篇文章要说的Callable接口就是其中一种。

该部分内容,在我之前的文章《Java中线程创建方式》中也有部分提及,这里主要通过实例来只管说明,直接看实例也挺不错,简明易懂。

因为该接口简单明了,这里直接附上源码。

一、源码

package java.util.concurrent;

/**
 * A task that returns a result and may throw an exception.
 * Implementors define a single method with no arguments called
 * {@code call}.
 *
 * <p>The {@code Callable} interface is similar to {@link
 * java.lang.Runnable}, in that both are designed for classes whose
 * instances are potentially executed by another thread.  A
 * {@code Runnable}, however, does not return a result and cannot
 * throw a checked exception.
 *
 * <p>The {@link Executors} class contains utility methods to
 * convert from other common forms to {@code Callable} classes.
 *
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> the result type of method {@code call}
 */
@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

简单介绍:
  返回结果并可能引发异常的任务。实现者定义了一个没有参数的方法call。
  Callable接口类似于Runnable,因为它们都是为那些实例可能由另一个线程执行的类设计的。然而,Runnable不会返回结果,也不会抛出检查异常。
  Executors类包含将其他通用形式转换为可调用类的实用程序方法。

二、创建步骤

(1)创建Callable接口的实现类,并实现call()方法,然后创建该实现类的实例(从java8开始可以直接使用Lambda表达式创建Callable对象)。
(2)使用FutureTask类来包装Callable对象,该FutureTask对象封装了Callable对象的call()方法的返回值
(3)使用FutureTask对象作为Thread对象的target创建并启动线程(因为FutureTask实现了Runnable接口)
(4)调用FutureTask对象的get()方法来获得子线程执行结束后的返回值

三、实例

实例一:正常创建

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

public class ThreadTest implements Callable<String> {
    private int count = 20;
    @Override
    public String call() {
        for (int i = count; i > 0; i--) {
            System.out.println(Thread.currentThread().getName()+"当前数目:" + i);
        }
        return "Game over!!!";
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Callable<String> callable  =new ThreadTest();
        FutureTask <String>futureTask=new FutureTask<>(callable);
        Thread mThread=new Thread(futureTask);
        mThread.start();
        System.out.println(futureTask.get());
    }
}

实例二:Lambda表达式创建

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

public class ThreadTest implements Callable<String> {
    private int count = 20;
    @Override
    public String call() {
        for (int i = count; i > 0; i--) {
            System.out.println(Thread.currentThread().getName()+"当前数目:" + i);
        }
        return "Game over!!!";
    }
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Callable<String> callable  =new ThreadTest();
        FutureTask <String>futureTask=new FutureTask(() -> callable.call());
        new Thread(futureTask,"ThreadName").start();
        System.out.println(futureTask.get());
    }
}

实例一和二的运行结果如下,区别是实例二自定义了一个线程名称:

ThreadName当前数目:20
ThreadName当前数目:19
ThreadName当前数目:18
ThreadName当前数目:17
ThreadName当前数目:16
ThreadName当前数目:15
ThreadName当前数目:14
ThreadName当前数目:13
ThreadName当前数目:12
ThreadName当前数目:11
ThreadName当前数目:10
ThreadName当前数目:9
ThreadName当前数目:8
ThreadName当前数目:7
ThreadName当前数目:6
ThreadName当前数目:5
ThreadName当前数目:4
ThreadName当前数目:3
ThreadName当前数目:2
ThreadName当前数目:1
Game over!!!

实例三:多线程状态(这里用两个线程为例)

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadTest implements Callable<String> {
    AtomicInteger count = new AtomicInteger(10000);
    private int count0 = 0;

    public String call() {
        while (count.get() > 0){
            System.out.println(Thread.currentThread().getName()+"当前数目:" + count.getAndDecrement());
            System.out.println(++count0);
        }
        return "Game over!!!";
    }
    public static void main(String[] args) {
        Callable<String> callable  =new ThreadTest();
        FutureTask<String> feature1 = new FutureTask(()-> callable.call());
        FutureTask<String> feature2 = new FutureTask(()-> callable.call());
        new Thread(feature1,"######ThreadName1").start();
        new Thread(feature2,"######ThreadName2").start();
        try {
            System.out.println("子线程1的返回值:" + feature1.get());
            System.out.println("子线程2的返回值:" + feature1.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

为方便观察,这里定义了一个原子数10000,结果是原子递减的。

四、优劣

(1)优势:
  线程类只是实现了Runnable接口或Callable接口,还可以继承其他类。在这种方式下,多个线程可以共享同一个target对象,适合多个相同线程来处理同一份资源的情况。
(2)劣势:
  编程稍微复杂,如果要访问当前线程,则必须使用Thread.currentThread()方法。

注:一般推荐采用实现接口的方式来创建多线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值