常德建设网站多少钱,西安网站建设瑞信,沈阳市官网,企业所得税税率2019文章目录1. Callable接口源码2. Future接口的源码3. RunnableFuture接口和FutureTask实现类4. 利用线程池和Callable接口实现异步执行任务5. 利用CompleteFutable实现多线程异步任务执行1. Callable接口源码
FunctionalInterface
public interface CallableV {// 这个…
文章目录1. Callable接口源码2. Future接口的源码3. RunnableFuture接口和FutureTask实现类4. 利用线程池和Callable接口实现异步执行任务5. 利用CompleteFutable实现多线程异步任务执行1. Callable接口源码
FunctionalInterface
public interface CallableV {// 这个call()方法有返回值且声明了受检异常可以直接抛出Exception异常V call() throws Exception;
}2. Future接口的源码
public interface FutureV {// 取消异步执行中的任务boolean cancel(boolean mayInterruptIfRunning);boolean isCancelled();// 判断异步任务是否执行成功boolean isDone();// 获取异步任务完成后的结果V get() throws InterruptedException, ExecutionException;V get(long timeout, TimeUnit unit)throws InterruptedException, ExecutionException, TimeoutException;
}Future接口中的方法
get()获取异步任务执行的结果。注意这个方法的调用是阻塞性的。如果异步任务没有执行完成异步结果获取线程调用线程会一直被阻塞一直阻塞到异步任务执行完成其异步结果返回给调用线程。
get(Long timeout,TimeUnit unit)设置时限调用线程阻塞性地获取异步任务执行的结果。该方法的调用也是阻塞性的但是结果获取线程调用线程会有一个阻塞时长限制不会无限制地阻塞和等待如果其阻塞时间超过设定的timeout时间该方法将抛出异常调用线程可捕获此异常。
boolean isDone()获取异步任务的执行状态。如果任务执行结束就返回true。
boolean isCancelled()获取异步任务的取消状态。如果任务完成前被取消就返回true。
boolean cancel(boolean mayInterruptRunning)取消异步任务的执行。
3. RunnableFuture接口和FutureTask实现类
如何使用Callable接口创建线程呢
public interface RunnableFutureV extends Runnable, FutureV {void run();
}RunnableFuture只是一个接口无法直接创建对象如果需要创建对象就需用到它的实现类——FutureTask。
public class FutureTaskV implements RunnableFutureV {private CallableV callable;// 构造方法public FutureTask(CallableV callable) {if (callable null) throw new NullPointerException();// callable实例属性需要在FutureTask实例构造时进行初始化this.callable callable;this.state NEW; }
}RunnableFuture接口实现了2个目标
(1) RunnableFuture通过继承Runnable接口从而保证了其实例可以作为Thread线程实例的target目标 (2) RunnableFuture通过继承Future接口从而保证了可以获取未来的异步执行结果。
首先通过实现Runnable接口的方式创建一个异步执行任务
public class CallableTaskDemo implements Callable {// call()方法有返回值并且可以抛出Exception异常Overridepublic String call() throws Exception {System.out.println(实现Callable接口来编写异步执行任务);Thread.sleep(1000);return 返回线程执行结果;}
}方式1通过Thread类创建线程执行异步任务
public class CallableDemo {public static void main(String[] args) throws ExecutionException, InterruptedException {// 创建异步执任务实例Callable callable new CallableTaskDemo();// 初始化callable实例属性FutureTask futureTask new FutureTask(callable);// 创建线程执行异步任务Thread thread new Thread(futureTask);thread.start();System.out.println(获取异步执行任务结果futureTask.get());// 获取异步执行任务结果返回线程执行结果}
}方式2通过线程池创建线程并提交异步执行任务
public class CallableDemo2 {// 通过线程池创建3个线程private static ExecutorService executorService Executors.newFixedThreadPool(3);public static void main(String[] args) throws ExecutionException, InterruptedException {// 通过线程池的submit()方法提交异步执行任务有返回结果Future submit executorService.submit(new CallableTaskDemo());// 获取返回结果System.out.println(submit.get());}
}对于Calleble来说Future和FutureTask均可以用来获取任务执行结果不过Future是个接口FutureTask是Future的具体实现而且FutureTask还间接实现了Runnable接口也就是说FutureTask可以作为Runnable任务提交给线程池。
4. 利用线程池和Callable接口实现异步执行任务
1、定义3个线程执行任务
public class FirstCallableTask implements CallableString {// call()方法有返回值并且可以抛出Exception异常Overridepublic String call() throws Exception {System.out.println(实现 First Callable接口来编写异步执行任务);Thread.sleep(1000);return 返回 First Callable 接口线程执行结果;}
}public class SecondCallableTask implements CallableString {Overridepublic String call() throws Exception {System.out.println(实现 Second Callable接口来编写异步执行任务);Thread.sleep(1000);return 返回 Second Callable 接口线程执行结果;}
}public class ThirdCallableTask implements CallableString {Overridepublic String call() throws Exception {System.out.println(实现 Third Callable接口来编写异步执行任务);Thread.sleep(1000);return 返回 Third Callable 接口线程执行结果;}
}2、定义线程池提交线程任务
Service
Slf4j
public class BeanLoadService implements ApplicationContextAware, ApplicationListenerContextStoppedEvent {private ApplicationContext applicationContext;// 定义一个线程池private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR new ThreadPoolExecutor(5,7,4,TimeUnit.SECONDS,new LinkedBlockingQueue(),new ThreadFactoryBuilder().setNamePrefix(BeanLoadService.class.getSimpleName() -pool-%d).setDaemon(true).build(),new ThreadPoolExecutor.DiscardOldestPolicy());public MapString,Integer richInfo() {CallableString firstCallable new FirstCallableTask();CallableString secondCallable new SecondCallableTask();CallableString thirdCallable new ThirdCallableTask();ListCallableString callableList new ArrayList();callableList.add(firstCallable);callableList.add(secondCallable);callableList.add(thirdCallable);try {ListFutureString futures THREAD_POOL_EXECUTOR.invokeAll(callableList, 1, TimeUnit.MINUTES);for (FutureString future : futures) {try {System.out.println(future.get());} catch (Exception e) {log.warn(incident delay data,future get warn, e);}}} catch (Exception e) {log.warn(incident delay data warn , e);}}Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext applicationContext;}Overridepublic void onApplicationEvent(ContextStoppedEvent contextStoppedEvent) {try {THREAD_POOL_EXECUTOR.shutdown();} catch (Exception e) {log.error(停止线程池失败, e);}}
}3、测试
SpringBootTest
RunWith(SpringRunner.class)
public class BeanLoadServiceTest {Autowiredprivate BeanLoadService beanLoadService;Testpublic void test(){beanLoadService.richInfo();}
}实现 First Callable接口来编写异步执行任务 实现 Second Callable接口来编写异步执行任务 实现 Third Callable接口来编写异步执行任务 返回 First Callable 接口线程执行结果 返回 Second Callable 接口线程执行结果 返回 Third Callable 接口线程执行结果 4、定义线程池提交线程任务内部类
Service
Slf4j
public class BeanLoadService implements ApplicationContextAware, ApplicationListenerContextStoppedEvent {private ApplicationContext applicationContext;// 定义一个线程池private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR new ThreadPoolExecutor(5,7,4,TimeUnit.SECONDS,new LinkedBlockingQueue(),new ThreadFactoryBuilder().setNamePrefix(BeanLoadService.class.getSimpleName() -pool-%d).setDaemon(true).build(),new ThreadPoolExecutor.DiscardOldestPolicy());public MapString,Integer richInfo() {CallableString firstCallable getFirstCallable();CallableString secondCallable getSecondCallable();CallableString thirdCallable getThirdCallable();ListCallableString callableList new ArrayList();callableList.add(firstCallable);callableList.add(secondCallable);callableList.add(thirdCallable);try {ListFutureString futures THREAD_POOL_EXECUTOR.invokeAll(callableList, 1, TimeUnit.MINUTES);for (FutureString future : futures) {try {System.out.println(future.get());} catch (Exception e) {log.warn(incident delay data,future get warn, e);}}} catch (Exception e) {log.warn(incident delay data warn , e);}}private CallableString getThirdCallable() {CallableString callable new CallableString() {Overridepublic String call() throws Exception {System.out.println(实现 Third Callable接口来编写异步执行任务);Thread.sleep(1000);return 返回 Third Callable 接口线程执行结果;}};}private CallableString getSecondCallable() {CallableString callable new CallableString() {Overridepublic String call() throws Exception {System.out.println(实现 Second Callable接口来编写异步执行任务);Thread.sleep(1000);return 返回 Second Callable 接口线程执行结果;};};return callable;}private CallableString getFirstCallable() {CallableString callable new CallableString() {Overridepublic String call() throws Exception {System.out.println(实现 First Callable接口来编写异步执行任务);Thread.sleep(1000);return 返回 First Callable 接口线程执行结果;}};return callable;}Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext applicationContext;}Overridepublic void onApplicationEvent(ContextStoppedEvent contextStoppedEvent) {try {THREAD_POOL_EXECUTOR.shutdown();} catch (Exception e) {log.error(停止线程池失败, e);}}
}5、定义线程池提交任务Java 8
Service
Slf4j
public class BeanLoadService implements ApplicationContextAware, ApplicationListenerContextStoppedEvent {private ApplicationContext applicationContext;// 定义一个线程池private static final ThreadPoolExecutor THREAD_POOL_EXECUTOR new ThreadPoolExecutor(5,7,4,TimeUnit.SECONDS,new LinkedBlockingQueue(),new ThreadFactoryBuilder().setNamePrefix(BeanLoadService.class.getSimpleName() -pool-%d).setDaemon(true).build(),new ThreadPoolExecutor.DiscardOldestPolicy());public void richInfo() {CallableString firstCallable getFirstCallable();CallableString secondCallable getSecondCallable();CallableString thirdCallable getThirdCallable();ListCallableString callableList new ArrayList();callableList.add(firstCallable);callableList.add(secondCallable);callableList.add(thirdCallable);try {ListFutureString futures THREAD_POOL_EXECUTOR.invokeAll(callableList, 1, TimeUnit.MINUTES);for (FutureString future : futures) {try {System.out.println(future.get());} catch (Exception e) {log.warn(incident delay data,future get warn, e);}}} catch (Exception e) {log.warn(incident delay data warn , e);}}private CallableString getThirdCallable() {CallableString callable ()-{System.out.println(实现 Third Callable接口来编写异步执行任务);Thread.sleep(1000);return 返回 Third Callable 接口线程执行结果;};return callable;}private CallableString getSecondCallable() {CallableString callable ()- {System.out.println(实现 Second Callable接口来编写异步执行任务);Thread.sleep(1000);return 返回 Second Callable 接口线程执行结果;};return callable;}private CallableString getFirstCallable() {CallableString callable () - {System.out.println(实现 First Callable接口来编写异步执行任务);Thread.sleep(1000);return 返回 First Callable 接口线程执行结果;};return callable;}Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext applicationContext;}Overridepublic void onApplicationEvent(ContextStoppedEvent contextStoppedEvent) {try {THREAD_POOL_EXECUTOR.shutdown();} catch (Exception e) {log.error(停止线程池失败, e);}}
}5. 利用CompleteFutable实现多线程异步任务执行
在 Java 8 中, 新增加了一个包含 50 个方法左右的类: CompletableFuture 提供了非常强大的Future 的扩展功能 可以帮助我们简化异步编程的复杂性 提供了函数式编程的能力 可以通过回调的方式处理计算结果 并且提供了转换和组合 CompletableFuture 的方法。CompletableFuture 类实现了 Future 接口 所以你还是可以像以前一样通过get方法阻塞或者轮询的方式获得结果 但是这种方式不推荐使用。
CompletableFuture 和 FutureTask 同属于 Future 接口的实现类 都可以获取线程的执行结果。
CompletableFuture 提供了四个静态方法来创建一个异步操作
runXxxx 都是没有返回结果的 supplyXxx 都是可以获取返回结果的可以传入自定义的线程池 否则就用默认的线程池 。
//子任务包装一个Runnable实例并调用ForkJoinPool.commonPool()线程池来执行
public static CompletableFutureVoid runAsync(Runnable runnable)//子任务包装一个Runnable实例并调用指定的executor线程池来执行
public static CompletableFutureVoid runAsync(Runnable runnable, Executor executor)//子任务包装一个Supplier实例并调用ForkJoinPool.commonPool()线程池来执行
public static U CompletableFutureU supplyAsync(SupplierU supplier)//子任务包装一个Supplier实例并使用指定的executor线程池来执行
public static U CompletableFutureU supplyAsync(SupplierU supplier, Executor executor)Service
Slf4j
public class BeanLoadService {public void getInfo() {ListCompletableFutureString futures new ArrayList();CompletableFutureString firstFuture CompletableFuture.supplyAsync(() - {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}return 返回 First Callable 接口线程执行结果;});futures.add(firstFuture);CompletableFutureString secondFuture CompletableFuture.supplyAsync(() - {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}return 返回 Second Callable 接口线程执行结果;});futures.add(secondFuture);CompletableFutureString thirdFuture CompletableFuture.supplyAsync(() - {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}return 返回 Third Callable 接口线程执行结果;});futures.add(thirdFuture);try {futures.forEach(future - {try {System.out.println(future.get());} catch (Exception e) {log.warn(incident delay data,future get warn, e);}});} catch (Exception e) {log.warn(incident delay data warn , e);}}
}
文章转载自: http://www.morning.lsnnc.cn.gov.cn.lsnnc.cn http://www.morning.fqzz3.cn.gov.cn.fqzz3.cn http://www.morning.clfct.cn.gov.cn.clfct.cn http://www.morning.pqcrz.cn.gov.cn.pqcrz.cn http://www.morning.slwfy.cn.gov.cn.slwfy.cn http://www.morning.gwjnm.cn.gov.cn.gwjnm.cn http://www.morning.rgnp.cn.gov.cn.rgnp.cn http://www.morning.kfwqd.cn.gov.cn.kfwqd.cn http://www.morning.hhnhb.cn.gov.cn.hhnhb.cn http://www.morning.zqbrd.cn.gov.cn.zqbrd.cn http://www.morning.cnqwn.cn.gov.cn.cnqwn.cn http://www.morning.kkjlz.cn.gov.cn.kkjlz.cn http://www.morning.yhxhq.cn.gov.cn.yhxhq.cn http://www.morning.zgdnd.cn.gov.cn.zgdnd.cn http://www.morning.krxzl.cn.gov.cn.krxzl.cn http://www.morning.rlbg.cn.gov.cn.rlbg.cn http://www.morning.ldzxf.cn.gov.cn.ldzxf.cn http://www.morning.pqqzd.cn.gov.cn.pqqzd.cn http://www.morning.qgghr.cn.gov.cn.qgghr.cn http://www.morning.kxypt.cn.gov.cn.kxypt.cn http://www.morning.ybgpk.cn.gov.cn.ybgpk.cn http://www.morning.ahlart.com.gov.cn.ahlart.com http://www.morning.pyncx.cn.gov.cn.pyncx.cn http://www.morning.pfnlc.cn.gov.cn.pfnlc.cn http://www.morning.hqxyt.cn.gov.cn.hqxyt.cn http://www.morning.ryrpq.cn.gov.cn.ryrpq.cn http://www.morning.dwfzm.cn.gov.cn.dwfzm.cn http://www.morning.ykrss.cn.gov.cn.ykrss.cn http://www.morning.ldpjm.cn.gov.cn.ldpjm.cn http://www.morning.kmwbq.cn.gov.cn.kmwbq.cn http://www.morning.qpmmg.cn.gov.cn.qpmmg.cn http://www.morning.ygkq.cn.gov.cn.ygkq.cn http://www.morning.hjwkq.cn.gov.cn.hjwkq.cn http://www.morning.dpqwq.cn.gov.cn.dpqwq.cn http://www.morning.fdmfn.cn.gov.cn.fdmfn.cn http://www.morning.ylmxs.cn.gov.cn.ylmxs.cn http://www.morning.nynpf.cn.gov.cn.nynpf.cn http://www.morning.jcwt.cn.gov.cn.jcwt.cn http://www.morning.cbndj.cn.gov.cn.cbndj.cn http://www.morning.rzbcz.cn.gov.cn.rzbcz.cn http://www.morning.dhbyj.cn.gov.cn.dhbyj.cn http://www.morning.ldmtq.cn.gov.cn.ldmtq.cn http://www.morning.jwrcz.cn.gov.cn.jwrcz.cn http://www.morning.yggdq.cn.gov.cn.yggdq.cn http://www.morning.rgpbk.cn.gov.cn.rgpbk.cn http://www.morning.rhkgz.cn.gov.cn.rhkgz.cn http://www.morning.yfrlk.cn.gov.cn.yfrlk.cn http://www.morning.cknws.cn.gov.cn.cknws.cn http://www.morning.rhqn.cn.gov.cn.rhqn.cn http://www.morning.ttryd.cn.gov.cn.ttryd.cn http://www.morning.mpmtz.cn.gov.cn.mpmtz.cn http://www.morning.ksjmt.cn.gov.cn.ksjmt.cn http://www.morning.qxljc.cn.gov.cn.qxljc.cn http://www.morning.duqianw.com.gov.cn.duqianw.com http://www.morning.pzqnj.cn.gov.cn.pzqnj.cn http://www.morning.sfphz.cn.gov.cn.sfphz.cn http://www.morning.rlwgn.cn.gov.cn.rlwgn.cn http://www.morning.pjwrl.cn.gov.cn.pjwrl.cn http://www.morning.ftmzy.cn.gov.cn.ftmzy.cn http://www.morning.vattx.cn.gov.cn.vattx.cn http://www.morning.cfynn.cn.gov.cn.cfynn.cn http://www.morning.qqbjt.cn.gov.cn.qqbjt.cn http://www.morning.smyxl.cn.gov.cn.smyxl.cn http://www.morning.fgsqz.cn.gov.cn.fgsqz.cn http://www.morning.cfocyfa.cn.gov.cn.cfocyfa.cn http://www.morning.yrsg.cn.gov.cn.yrsg.cn http://www.morning.kspfq.cn.gov.cn.kspfq.cn http://www.morning.sfphz.cn.gov.cn.sfphz.cn http://www.morning.htbbp.cn.gov.cn.htbbp.cn http://www.morning.mlfmj.cn.gov.cn.mlfmj.cn http://www.morning.xmxbm.cn.gov.cn.xmxbm.cn http://www.morning.gsqw.cn.gov.cn.gsqw.cn http://www.morning.kkrnm.cn.gov.cn.kkrnm.cn http://www.morning.blbys.cn.gov.cn.blbys.cn http://www.morning.jyknk.cn.gov.cn.jyknk.cn http://www.morning.lfsmf.cn.gov.cn.lfsmf.cn http://www.morning.bftr.cn.gov.cn.bftr.cn http://www.morning.trqsm.cn.gov.cn.trqsm.cn http://www.morning.dhpjq.cn.gov.cn.dhpjq.cn http://www.morning.xjmpg.cn.gov.cn.xjmpg.cn