当前位置: 移动技术网 > IT编程>开发语言>Java > Java中实现多线程关键词整理(总结)

Java中实现多线程关键词整理(总结)

2019年07月22日  | 移动技术网IT编程  | 我要评论

java中的runable,callable,future,futuretask,executorservice,excetor,excutors,threadpoolexcetor在这里对这些关键词,以及它们的用法做一个总结。

首先将它们分个类:

runable,callable
future,futuretask
executorservice,excetor,excutors,threadpoolexcetor

1. 关于ranable和callable

首先java中创建线程的方法有三种:

  1. 继承thread类,覆盖run方法
  2. 实现runable接口,实现run方法
  3. 实现callable接口,实现run方法

三种实现的优缺点:

继承thread,单继承的缘故,不能再继承其他类,获取当前线程this

实现runable接口,没有返回值,获取当前线程thread.currentthread()

实现callable接口,可通过future.get()获取返回值,获取当前线程 thread.currentthread()

继承thread,两个步骤:

class demothread extends thread {
  @override
  public void run() {
    super.run();
    // perform time-consuming operation...
  }
}
demothread t = new demothread();
t.start();
  • 继承thread类,覆盖run()方法。
  • 创建线程对象并用start()方法启动线程。

实现runable,一般使用如下:

new thread(new runnable() {
  @override
  public void run() {
    // do something
  }
}).start();

为了简单。

以上两种方式获取线程执行的结果相当麻烦,不能直接获取。jdk1.5增加了 callable, callable 的 call() 方法可以返回值和抛出异常。callable 可以返回装载有计算结果的 future 对象。
callable的源码:

public interface callable<v> {
  v call() throws exception;
}

callable的基本使用方法:

futuretask<integer> futuretask = new futuretask<integer>(new callable<integer>() {
  @override
  public integer call() throws exception {
    // do something
    return null;
  }
});
thread thread = new thread(futuretask);
thread.start();
integer result = futuretask.get();

运行 callable 任务可以拿到一个 future 对象,通过future的get()方法拿到线程执行的返回值。那么...future,

futuretask区别是什么,怎么使用?

->next()

2. 关于future和futuretask

为了获取线程的执行结果,引入了future的futuretask,那么他们是什么关系,如何使用?

future类位于java.util.concurrent包下,它是一个接口:

public interface future<v> {
  boolean cancel(boolean mayinterruptifrunning);
  boolean iscancelled();
  boolean isdone();
  v get() throws interruptedexception, executionexception;
  v get(long timeout, timeunit unit)
    throws interruptedexception, executionexception, timeoutexception;
}

future 定义了5个方法:

1)boolean cancel(boolean mayinterruptifrunning):试图取消对此任务的执行。如果任务已完成、或已取消,或者由于某些其他原因而无法取消,则此尝试将失败。当调用 cancel() 时,如果调用成功,而此任务尚未启动,则此任务将永不运行。如果任务已经启动,则 mayinterruptifrunning 参数确定是否应该以试图停止任务的方式来中断执行此任务的线程。此方法返回后,对 isdone() 的后续调用将始终返回 true。如果此方法返回 true,则对 iscancelled() 的后续调用将始终返回 true。

2)boolean iscancelled():如果在任务正常完成前将其取消,则返回 true。

3)boolean isdone():如果任务已完成,则返回 true。 可能由于正常终止、异常或取消而完成,在所有这些情况中,此方法都将返回 true。

4)v get()throws interruptedexception,executionexception:如有必要,等待计算完成,然后获取其结果。

5)v get(long timeout,timeunit unit) throws interruptedexception, executionexception, timeoutexception: 如有必要,最多等待为使计算完成所给定的时间之后,获取其结果(如果结果可用)。

总的来说future提供了三种功能:

判断任务是否完成;

能够中断任务;

能够获取任务执行结果。

重点:

runnablefuture继承了runnable接口和future接口,而futuretask实现了runnablefuture接口。

futuretask的实现:

public class futuretask<v> implements runnablefuture<v>

runnablefuture接口的实现:

public interface runnablefuture<v> extends runnable, future<v> {
  void run();
}

futuretask是future接口的一个唯一实现类。

除了可以用thread包装futuretask外,还有另一种使用方法:

executorservice executor = executors.newcachedthreadpool();
futuretask<integer> futuretask = new futuretask<integer>(new callable<integer>() {
  @override
  public integer call() throws exception {
    // do something
    return null;
  }
});
executor.submit(futuretask);
integer result = futuretask.get();

这里用到了executor 框架。

->next();

3. 关于executorservice,excetor,excutors,threadpoolexcetor

executor框架在java 5中被引入,executor 框架是一个根据一组执行策略调用、调度、执行和控制的异步任务的框架。
在说executor 框架之前我们需要引入一个新的概念——线程池(threadpoolexecutor):

public threadpoolexecutor(intcorepoolsize,
    int maximumpoolsize,
    long keepalivetime,
    timeunit unit,
    blockingqueue<runnable> workqueue,
    threadfactory threadfactory,
    rejectedexecutionhandler handler)

threadpoolexecutor是executors类的底层实现。

在jdk帮助文档中,有如此一段话:

“强烈建议程序员使用较为方便的 executors 工厂方法 executors.newcachedthreadpool()(无界线程池,可以进行自动线程回收)、executors.newfixedthreadpool(int)(固定大小线程池)和 executors.newsinglethreadexecutor()(单个后台线程),它们均为大多数使用场景预定义了设置。”

那么executorservice,excetor,excutors都是什么?
excetor是一个抽象层面的核心接口:

public interface executor {
  void execute(runnable command);
}

executorservice 接口 对 executor 接口进行了扩展,提供了返回 future 对象,终止,关闭线程池等方法。

public interface executorservice extends executor {
  void shutdown();
  <t> future<t> submit(callable<t> task);
  <t> future<t> submit(runnable task, t result);
  <t> list<future<t>> invokeall(collection<? extends callable<t>> tasks, long timeout, timeunit unit) throws interruptedexception;
}

executors 是一个工具类,类似于 collections。提供工厂方法来创建不同类型的线程池,比如 fixedthreadpool 或 cachedthreadpool。

public class executors {
  public static executorservice newfixedthreadpool(int nthreads) {
    return new threadpoolexecutor(nthreads, nthreads, 0l, timeunit.milliseconds,new linkedblockingqueue<runnable>());
    }
    
   public static executorservice newcachedthreadpool() {
    return new threadpoolexecutor(0, integer.max_value, 60l, timeunit.seconds, new synchronousqueue<runnable>());
    }
}

以上是对java多线程关键词的整理,不至于一团乱麻。

以上所述是小编给大家介绍的java中实现多线程关键词整理,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网