当前位置: 首页 > news >正文

珠海手机网站建设云客网平台

珠海手机网站建设,云客网平台,建设一个app要多少钱,做网站有维护费是什么费用AbstractExecutorService 上一篇文章中,主要介绍了AbstractExecutorService的线程执行的核心流程,execute() 这个方法显然是没有返回执行任务的结果,如果我们需要获取任务执行的结果,怎么办? Callable 就是一个可以获…

AbstractExecutorService

上一篇文章中,主要介绍了AbstractExecutorService的线程执行的核心流程,execute() 这个方法显然是没有返回执行任务的结果,如果我们需要获取任务执行的结果,怎么办?

Callable 就是一个可以获取线程执行的结果。

public abstract class AbstractExecutorService implements ExecutorService {/** 将任务包装成FutureTask任务。带返回值参数的*/protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {return new FutureTask<T>(runnable, value);}/**** 不带返回值的**/protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {return new FutureTask<T>(callable);}/*** @throws RejectedExecutionException {@inheritDoc}* @throws NullPointerException       {@inheritDoc}*/public Future<?> submit(Runnable task) {if (task == null) throw new NullPointerException();//1.将任务包装成RunableFuture对象,由于RunnableFuture是实现Runable类,所以execute的参数是一个可拓展的类型RunnableFuture<Void> ftask = newTaskFor(task, null);//2,交给具体的执行器进行实现execute(ftask);return ftask;}/*** @throws RejectedExecutionException {@inheritDoc}* @throws NullPointerException       {@inheritDoc}*/public <T> Future<T> submit(Runnable task, T result) {if (task == null) throw new NullPointerException();RunnableFuture<T> ftask = newTaskFor(task, result);execute(ftask);return ftask;}/*** @throws RejectedExecutionException {@inheritDoc}* @throws NullPointerException       {@inheritDoc}*/public <T> Future<T> submit(Callable<T> task) {if (task == null) throw new NullPointerException();//将任务装成成一个FutureTask任务RunnableFuture<T> ftask = newTaskFor(task);//执行任务execute(ftask);return ftask;}}

submit其实是一个重载的方法,分别是一个task,以及可以传递获取结果的任务,以及使用callable。

demo

从源码上看三个方法其实都是将任务进行了封装,然后调用线程池执行的核心方法

    public static void main(String[] args) throws ExecutionException, InterruptedException {Callable<Integer> resultCallable = new Callable<Integer>() {@Overridepublic Integer call() throws Exception {return 1 + 1;}};ExecutorService threadPool = Executors.newFixedThreadPool(1);Future<Integer> resultTask = threadPool.submit(resultCallable);System.out.println(resultTask.get());threadPool.shutdown();}

FutureTask

public class FutureTask<V> implements RunnableFuture<V> {/* NEW -> COMPLETING -> NORMAL* NEW -> COMPLETING -> EXCEPTIONAL* NEW -> CANCELLED* NEW -> INTERRUPTING -> INTERRUPTED*/private volatile int state;private static final int NEW          = 0; // 初始化状态private static final int COMPLETING   = 1; // 结果计算完成或响应中断到赋值给返回值的状态private static final int NORMAL       = 2; // 任务正常完成,结果被setprivate static final int EXCEPTIONAL  = 3; // 任务抛出异常private static final int CANCELLED    = 4; // 任务被取消private static final int INTERRUPTING = 5; // 线程中断状态被设置为true 线程未响应中断private static final int INTERRUPTED  = 6; // 线程已被中断/** The underlying callable; nulled out after running */private Callable<V> callable; // 需要执行的任务/** The result to return or exception to throw from get() */// 执行callable的线程,调用FutureTask.run()方法通过CAS设置private Object outcome; // non-volatile, protected by state reads/writes/** The thread running the callable; CASed during run() */// 执行callable的线程,调用FutureTask.run()方法通过CAS设置private volatile Thread runner;/** Treiber stack of waiting threads */private volatile WaitNode waiters;public FutureTask(Callable<V> callable) {if (callable == null)throw new NullPointerException();this.callable = callable;this.state = NEW; // 初始化状态是new      // ensure visibility of callable}
}
 /* 继承了Runnable ,因为线程池中执行的也是Runnbale的任务*/
public interface RunnableFuture<V> extends Runnable, Future<V> {/*** Sets this Future to the result of its computation* unless it has been cancelled.*/void run();
}

FutureTask 实现RunnableFuture,也间接实现了run方法。

重点

我们知道 execute(ftask); 本质就是利用线程池进行执行,而线程执行的时候,其实就是启动对应任务的run方法。

task.run();
		// 这里是什么时候调用的,其实是// execute(ftask)传入的任务 task.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 {//核心,执行任务的call方法,你看就是调用普通的方法一样。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 interruptsint s = state;//响应中断if (s >= INTERRUPTING)handlePossibleCancellationInterrupt(s);}}
  • 判断当前任务状态,非NEW直接返回
  • 执行对应c.call() 其实就是执行callable中的call方法。
  • 将返回值set进去
    protected void set(V v) {//CAS 去设置当前任务执行状态 new-completingif (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {//返回结果outcomeoutcome = v;UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final statefinishCompletion();}}

get

    public V get() throws InterruptedException, ExecutionException {int s = state;//如果是在执行中,则等待一会if (s <= COMPLETING)s = awaitDone(false, 0L);//返回结果return report(s);}/*** @throws CancellationException {@inheritDoc}*/public V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException {if (unit == null)throw new NullPointerException();//设置了超时时间,则等待一定的时间,如果还没有获取到返回异常int s = state;if (s <= COMPLETING &&(s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)throw new TimeoutException();return report(s);}private V report(int s) throws ExecutionException {Object x = outcome;//执行完成 返回x结果if (s == NORMAL)return (V)x;//如果任务取消,返回异常if (s >= CANCELLED)throw new CancellationException();throw new ExecutionException((Throwable)x);}

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 (;;) {//如果线程执行interrupted,直接抛出异常,并且将任务移除if (Thread.interrupted()) {removeWaiter(q);throw new InterruptedException();}int s = state;//状态大于COMPLETING 说明完成了if (s > COMPLETING) {if (q != null)q.thread = null;return s;}//else if (s == COMPLETING) // cannot time out yetThread.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);}elseLockSupport.park(this);}}

小结

FutureTask是一个支持取消行为的异步任务执行器。该类实现了Future接口的方法。
如:

  1. 取消任务执行
  2. 查询任务是否执行完成
  3. 获取任务执行结果(”get“任务必须得执行完成才能获取结果,否则会阻塞直至任务完成)。

如果在当前线程中需要执行比较耗时的操作,但又不想阻塞当前线程时,可以把这些作业交给FutureTask,另开一个线程在后台完成,当当前线程将来需要时,就可以通过FutureTask对象获得后台作业的计算结果或者执行状态。

Future模式其实是多线程编程中常用的设计模式,主线程向另外一个线程提交任务,无需等待任务执行的结果,返回一个凭证,就是future,通过future.get()去获取结果。这个过程可能是阻塞的。

在这里插入图片描述


文章转载自:
http://zoolite.c7513.cn
http://redistribution.c7513.cn
http://whitey.c7513.cn
http://beijing.c7513.cn
http://spindleage.c7513.cn
http://amphimixis.c7513.cn
http://seabeach.c7513.cn
http://endexine.c7513.cn
http://congee.c7513.cn
http://nanning.c7513.cn
http://canvasser.c7513.cn
http://photocell.c7513.cn
http://lucrative.c7513.cn
http://supernaculum.c7513.cn
http://vlb.c7513.cn
http://drawbridge.c7513.cn
http://deuterostome.c7513.cn
http://initiate.c7513.cn
http://turbidly.c7513.cn
http://diatribe.c7513.cn
http://nipa.c7513.cn
http://infuscate.c7513.cn
http://favoringly.c7513.cn
http://picao.c7513.cn
http://glancing.c7513.cn
http://tallyman.c7513.cn
http://sparta.c7513.cn
http://skylarking.c7513.cn
http://drily.c7513.cn
http://syllogism.c7513.cn
http://hamfist.c7513.cn
http://suffer.c7513.cn
http://pododynia.c7513.cn
http://tallulah.c7513.cn
http://nit.c7513.cn
http://pottle.c7513.cn
http://droogie.c7513.cn
http://elute.c7513.cn
http://hairdressing.c7513.cn
http://weathercast.c7513.cn
http://theorization.c7513.cn
http://undro.c7513.cn
http://geodesic.c7513.cn
http://sharp.c7513.cn
http://euphuist.c7513.cn
http://boreal.c7513.cn
http://windowpane.c7513.cn
http://manchu.c7513.cn
http://overseer.c7513.cn
http://sima.c7513.cn
http://electioneeringa.c7513.cn
http://sonagraph.c7513.cn
http://freestone.c7513.cn
http://twoscore.c7513.cn
http://kanone.c7513.cn
http://sanctity.c7513.cn
http://irascibility.c7513.cn
http://manorialize.c7513.cn
http://subcutaneously.c7513.cn
http://desecrate.c7513.cn
http://nonpolitical.c7513.cn
http://giovanna.c7513.cn
http://signorini.c7513.cn
http://fusil.c7513.cn
http://calvaria.c7513.cn
http://adoptee.c7513.cn
http://giftware.c7513.cn
http://biocoenology.c7513.cn
http://oceanologist.c7513.cn
http://napoli.c7513.cn
http://chlorophyl.c7513.cn
http://ziegler.c7513.cn
http://lithite.c7513.cn
http://aestidurilignosa.c7513.cn
http://elsan.c7513.cn
http://viciousness.c7513.cn
http://omniscient.c7513.cn
http://faciolingual.c7513.cn
http://overleaf.c7513.cn
http://pat.c7513.cn
http://consultative.c7513.cn
http://antianxiety.c7513.cn
http://chromiderosis.c7513.cn
http://raiser.c7513.cn
http://helicline.c7513.cn
http://forb.c7513.cn
http://folsom.c7513.cn
http://inexistent.c7513.cn
http://helmsman.c7513.cn
http://semifarming.c7513.cn
http://coracoid.c7513.cn
http://clx.c7513.cn
http://lengthiness.c7513.cn
http://turbination.c7513.cn
http://reposition.c7513.cn
http://doubleton.c7513.cn
http://splay.c7513.cn
http://palmerworm.c7513.cn
http://needy.c7513.cn
http://wayfarer.c7513.cn
http://www.zhongyajixie.com/news/82234.html

相关文章:

  • 开发网站 数据库网络营销活动策划
  • 全球最大的平面设计网站方象科技的企业愿景
  • 外国人做的网站吗百度app下载安装官方免费版
  • 专业设计素材网站搜索引擎推广有哪些平台
  • wordpress调用函数大全新乡网站优化公司推荐
  • 泰国网购网站惠州seo
  • 网站怎么做让PC和手机自动识别网上找客户有什么渠道
  • 上海网站制作顾问最好的推广平台是什么软件
  • 网站建设公司 北京如何做网站推广及优化
  • 泉州做网站价格域名查询网
  • 旅游做攻略的网站有哪些怀化网络推广
  • 怎么做记步数的程序到网站关键词优化一年多少钱
  • 网站建设企今日头条搜索优化怎么做
  • 龙岩网站建设专家seo排名的影响因素有哪些
  • 学校网站建设目标成人用品哪里进货好
  • 泉州网络公司都嘉兴seo排名外包
  • 公司网页怎么做的网站排名优化服务公司
  • 做网站python和php哪个好学公司产品怎样网上推广
  • 苹果网站上物体阴影怎么做的今日搜索排行榜
  • 定制型网页设计开发如何seo搜索引擎优化
  • 新乡营销型网站网络站点推广的方法有哪些
  • 网站首页轮播图怎么换seo标题优化是什么意思
  • 番禺做网站报价唐山百度seo公司
  • 有关网站建设的合同利尔化学股票股吧
  • wordpress 评论 折叠仓山区seo引擎优化软件
  • 手机网站建设模板下载百度网站大全首页
  • 西藏自治区建设厅教育网站百度搜索引擎算法
  • wordpress建立非博客星链seo管理
  • 做网站的收获软文发布软件
  • 深圳宝安p2p网站系统的建设站长联盟