Java中的Runnable、Callable、Future、FutureTask的区别与示例

Java中存在Runnable、Callable、Future、FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别。

Runnable

其中Runnable应该是我们最熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值。然后使用某个线程去执行该runnable即可实现多线程,Thread类在调用start()函数后就是执行的是Runnable的run()函数。Runnable的声明如下 :

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object‘s
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

Callable

Callable与Runnable的功能大致相似,Callable中有一个call()函数,但是call()函数有返回值,而Runnable的run()函数不能将结果返回给客户程序。Callable的声明如下 :

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()函数返回的类型就是客户程序传递进来的V类型。

Future

Executor就是Runnable和Callable的调度容器,Future就是对于具体的Runnable或者Callable任务的执行结果进行

取消、查询是否完成、获取结果、设置结果操作。get方法会阻塞,直到任务返回结果(Future简介)。Future声明如下
:

/**
* @see FutureTask
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> The result type returned by this Future‘s <tt>get</tt> method
 */
public interface Future<V> {

    /**
     * Attempts to cancel execution of this task.  This attempt will
     * fail if the task has already completed, has already been cancelled,
     * or could not be cancelled for some other reason. If successful,
     * and this task has not started when <tt>cancel</tt> is called,
     * this task should never run.  If the task has already started,
     * then the <tt>mayInterruptIfRunning</tt> parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.     *
     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * Returns <tt>true</tt> if this task was cancelled before it completed
     * normally.
     */
    boolean isCancelled();

    /**
     * Returns <tt>true</tt> if this task completed.
     *
     */
    boolean isDone();

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @return the computed result
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * Waits if necessary for at most the given time for the computation
     * to complete, and then retrieves its result, if available.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

FutureTask

FutureTask则是一个RunnableFuture<V>,而RunnableFuture实现了Runnbale又实现了Futrue<V>这两个接口,

public class FutureTask<V> implements RunnableFuture<V>

RunnableFuture

public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}

另外它还可以包装Runnable和Callable<V>, 由构造函数注入依赖。

    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);
        this.state = NEW;       // ensure visibility of callable
    }

可以看到,Runnable注入会被Executors.callable()函数转换为Callable类型,即FutureTask最终都是执行Callable类型的任务。该适配函数的实现如下 :

    public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    }

RunnableAdapter适配器

    /**
     * A callable that runs given task and returns given result
     */
    static final class RunnableAdapter<T> implements Callable<T> {
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {
            task.run();
            return result;
        }
    }

由于FutureTask实现了Runnable,因此它既可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行。

并且还可以直接通过get()函数获取执行结果,该函数会阻塞,直到结果返回。因此FutureTask既是Future、

Runnable,又是包装了Callable(
如果是Runnable最终也会被转换为Callable ), 它是这两者的合体。

简单示例

 package com.effective.java.concurrent.task;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 *
 * @author mrsimple
 *
 */
public class RunnableFutureTask {

	/**
	 * ExecutorService
	 */
	static ExecutorService mExecutor = Executors.newSingleThreadExecutor();

	/**
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		runnableDemo();
		futureDemo();
	}

	/**
	 * runnable, 无返回值
	 */
	static void runnableDemo() {

		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println("runnable demo : " + fibc(20));
			}
		}).start();
	}

	/**
	 * 其中Runnable实现的是void run()方法,无返回值;Callable实现的是 V
	 * call()方法,并且可以返回执行结果。其中Runnable可以提交给Thread来包装下
	 * ,直接启动一个线程来执行,而Callable则一般都是提交给ExecuteService来执行。
	 */
	static void futureDemo() {
		try {
			/**
			 * 提交runnable则没有返回值, future没有数据
			 */
			Future<?> result = mExecutor.submit(new Runnable() {

				@Override
				public void run() {
					fibc(20);
				}
			});

			System.out.println("future result from runnable : " + result.get());

			/**
			 * 提交Callable, 有返回值, future中能够获取返回值
			 */
			Future<Integer> result2 = mExecutor.submit(new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					return fibc(20);
				}
			});

			System.out
					.println("future result from callable : " + result2.get());

			/**
			 * FutureTask则是一个RunnableFuture<V>,即实现了Runnbale又实现了Futrue<V>这两个接口,
			 * 另外它还可以包装Runnable(实际上会转换为Callable)和Callable
			 * <V>,所以一般来讲是一个符合体了,它可以通过Thread包装来直接执行,也可以提交给ExecuteService来执行
			 * ,并且还可以通过v get()返回执行结果,在线程体没有执行完成的时候,主线程一直阻塞等待,执行完则直接返回结果。
			 */
			FutureTask<Integer> futureTask = new FutureTask<Integer>(
					new Callable<Integer>() {
						@Override
						public Integer call() throws Exception {
							return fibc(20);
						}
					});
			// 提交futureTask
			mExecutor.submit(futureTask) ;
			System.out.println("future result from futureTask : "
					+ futureTask.get());

		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 效率底下的斐波那契数列, 耗时的操作
	 *
	 * @param num
	 * @return
	 */
	static int fibc(int num) {
		if (num == 0) {
			return 0;
		}
		if (num == 1) {
			return 1;
		}
		return fibc(num - 1) + fibc(num - 2);
	}

}

输出结果

Java中的Runnable、Callable、Future、FutureTask的区别与示例,布布扣,bubuko.com

时间: 2024-08-24 07:23:09

Java中的Runnable、Callable、Future、FutureTask的区别与示例的相关文章

Java中的Runnable、Callable、Future、FutureTask的区别

Java中存在Runnable.Callable.Future.FutureTask这几个与线程相关的类或者接口,在Java中也是比较重要的几个概念,我们通过下面的简单示例来了解一下它们的作用于区别. Runnable 其中Runnable应该是我们最熟悉的接口,它只有一个run()函数,用于将耗时操作写在其中,该函数没有返回值.然后使用某个线程去执行该runnable即可实现多线程,Thread类在调用start()函数后就是执行的是Runnable的run()函数.Runnable的声明如下

java中System.getenv和System.getProperties的区别

System.getenv获取的是系统的环境变量(就是用户在操作系统中设置的环境变量),windows和linux下环境变量的设置就不说了哦. System.getProperties获取的是系统的相关属性.在java api文档中已经列出了如下属性 如果我们要在java程序启动就能获取自定义的系统属性我们可以使用 java –Dname=zhuhui 这样我们就在系统属性中设置了名称为myname值为zhuhui的系统属性,那么就可以通过System.getProperty("name&quo

Java中final、finally、finalize的区别(转)

Java中final.finally.finalize的区别与用法,困扰了不少学习者,下面我们就这个问题进行一些探讨,希望对大家的学习有所帮助. 方法/步骤 1 简单区别: final用于声明属性,方法和类,分别表示属性不可交变,方法不可覆盖,类不可继承. finally是异常处理语句结构的一部分,表示总是执行. finalize是Object类的一个方法,在垃圾收集器执行的时候会调用被回收对象的此方法,供垃圾收集时的其他资源回收,例如关闭文件等. END 方法/步骤2 1 中等区别: 虽然这三

Java中字符串比较时==和equals的区别

==是比较两个字符串引用的地址是否相同,即是否指向同一个对象,而equals方法则比较字符串的内容是否相同. 例如String a = "abc"; String b = "abc"; a == b返回true,a.equals(b)同样返回true,这是为什么呢? 原来程序在运行时有一个字符串池,创建字符串时会先查找池中是否有相应的字符串,如果已经存在的话只需把引用指向它即可,如果没有则新建一个. 上例中创建a时,会在字符串池中首先创建一个"abc&qu

JAVA中 String 、StringBuffer和StringBuilder 的区别

String 内容定义成 final char[],只能在属性和构造函数中赋值,其它地方不能改变 :String 覆盖实现了 equals . StringBuffer 内容定义成了 char[] ,但没实现 equals. String 和 StringBuffer 的区别是: 1.String 通过构造新的String 实现可变字符串,而 StringBuffer 通过改变内部的内容属性来实现可变字符串. 2.new String("ABC").equals("ABC&q

JAVA中List、Map、Set的区别与选用

类层次关系如下: Collection ├List│├LinkedList│├ArrayList│└Vector│ └Stack└SetMap├Hashtable├HashMap └WeakHashMap 下面来分别介绍 Collection接口 Collection是最基本的集合接口,一个Collection代表一组Object,即Collection的元素(Elements).一些 Collection允许相同的元素而另一些不行.一些能排序而另一些不行.Java SDK不提供直接继承自Col

【Java学习笔记之二十九】Java中的&quot;equals&quot;和&quot;==&quot;的用法及区别

Java中的"equals"和"=="的用法及区别 在初学Java时,可能会经常碰到下面的代码: 1 String str1 = new String("hello"); 2 String str2 = new String("hello"); 3 System.out.println(str1==str2); 4 System.out.println(str1.equals(str2)); 为什么第4行和第5行的输出结果不一

java中String new和直接赋值的区别

    Java中String new和直接赋值的区别     对于字符串:其对象的引用都是存储在栈中的,如果是编译期已经创建好(直接用双引号定义的)的就存储在常量池中,如果是运行期(new出来的)才能确定的就存储在堆中.对于equals相等的字符串,在常量池中永远只有一份,在堆中有多份. 例如: String str1="ABC": 和String str2 = new String("ABC"); String str1="ABC" 可能创建

Java中String,StringBuffer和StringBuilder的区别(转载)

String 字符串常量StringBuffer 字符串变量(线程安全)StringBuilder 字符串变量(非线程安全) 简 要的说, String 类型和 StringBuffer 类型的主要性能区别其实在于 String 是不可变的对象, 因此在每次对 String 类型进行改变的时候其实都等同于生成了一个新的 String 对象,然后将指针指向新的 String 对象,所以经常改变内容的字符串最好不要用 String ,因为每次生成对象都会对系统性能产生影响,特别当内存中无引用对象多了