Runnable、Callable、Executor、ExecutorService、ScheduledExecutorService、Executors
来源:互联网 发布:哪些女装淘宝店铺推荐 编辑:程序博客网 时间:2024/05/29 02:24
本文是关于java.util.concurrent类库中任务、执行器(调度器/线程池)的相关测试用例,记录学习的脚步
使用pd画了个 主要的类图
主要测试类如下
RunnableTest.java
/** * */package com.undergrowth.util.concurrent;import org.junit.Test;/** * 测试Runnable 可执行的任务--> 本身并不执行,需外部调用执行 * * @author undergrowth * */public class RunnableTest {private Runnable runnable;private Thread thread;/** * 使用匿名类的方式构建可执行的任务 */@Testpublic void testRun() {// 匿名类runnable = new Runnable() {public void run() {// TODO Auto-generated method stubSystem.out.println("内部线程名:" + Thread.currentThread().getName());System.out.println("内部线程输出:" + "发生什么");}};// 执行任务runnable.run();System.out.println("外部线程名:" + Thread.currentThread().getName());}/** * 使用单独的线程构建可执行的任务 注意 start()与run()的区别 */@Testpublic void testThread() {// 构建另外线程执行thread = new Thread(new Runnable() {public void run() {// TODO Auto-generated method stubSystem.out.println("内部线程名:" + Thread.currentThread().getName());// System.out.println("内部线程输出:" + "发生什么");}}, "内部线程名称");// 使用start启动新线程 并发执行thread.start();System.out.println("外部线程名:" + Thread.currentThread().getName());// 使用run则 使用外部线程执行任务thread.run();}}/** * Runnable的实现类 * @author undergrowth * */class RunnableConcrete implements Runnable{public void run() {// TODO Auto-generated method stubSystem.out.println(Thread.currentThread().getName()+"\t"+RunnableConcrete.class.getSimpleName());}}
结果
testRun()
内部线程名:main内部线程输出:发生什么外部线程名:main
testThread()
外部线程名:main内部线程名:内部线程名称内部线程名:main
CallableTest.java
/** * */package com.undergrowth.util.concurrent;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.Executors;import org.junit.Test;/** * Callable-->返回结果并且可能抛出异常的任务 * * @author undergrowth * */public class CallableTest {private Callable<String> callable;/** * 使用调用者调用任务,同步执行 */@Testpublic void synCallable() {callable = new CallableConcrete<String>();try {System.out.println(callable.call());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 使用线程池进行任务调度 */@Testpublic void asynCallable(){callable = new CallableConcrete<String>();try {System.out.println(Executors.newCachedThreadPool().submit(callable).get());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();};}}/** * Callable的实现类 * * @author undergrowth * */class CallableConcrete<V> implements Callable<V> {@SuppressWarnings("unchecked")public V call() throws Exception {// TODO Auto-generated method stubreturn (V)(Thread.currentThread().getName()+"\t"+CallableConcrete.class.getSimpleName());}}
结果
syncCallable()
mainCallableConcrete
pool-1-thread-1CallableConcrete
可执行者
ExecutorTest.java
/** * */package com.undergrowth.util.concurrent;import java.util.Queue;import java.util.concurrent.Executor;import org.junit.Test;/** * Executor-->可执行者 * @author undergrowth * */public class ExecutorTest {private Executor executor;private Runnable runnable = new Runnable() {public void run() {// TODO Auto-generated method stubSystem.out.println(Thread.currentThread().getName());}};/** * 测试异步执行 */@Testpublic void asynExecuteTest() {System.out.println(Thread.currentThread().getName());executor = new AsynExecute();executor.execute(runnable);}/** * 测试同步执行 */@Testpublic void syncExecuteTest() {System.out.println(Thread.currentThread().getName());executor = new SyncExecute();executor.execute(runnable);}}/** * 构建单独线程执行 * 异步执行的任务 * @author undergrowth * */class AsynExecute implements Executor {public void execute(Runnable command) {// TODO Auto-generated method stubnew Thread(command, "单独的线程").start();}}/** * 使用调用线程线程执行任务 * 同步执行的任务 * @author undergrowth * */class SyncExecute implements Executor {public void execute(Runnable command) {// TODO Auto-generated method stubcommand.run();}}
结果
asynExecuteTest()
main单独的线程
syncExecuteTest()
mainmain
工厂类
ExecutorsTest.java
/** * */package com.undergrowth.util.concurrent;import java.util.ArrayList;import java.util.Collection;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.CancellationException;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.ThreadFactory;import java.util.concurrent.TimeUnit;import org.junit.Test;/** * Executors类--> 提供实用方法--> * 工厂类作用-->Executor、ExecutorService、ScheduledExecutorService、ThreadFactory、Callable * * @author undergrowth * */public class ExecutorsTest {// 可执行的任务 不可返回值private Runnable runnable = new RunnableConcrete();// 可执行的任务 可返回值private Callable<String> callable = new CallableConcrete<String>();// 线程工厂private ThreadFactory threadFactory;// 提供了执行任务、跟踪任务、关闭线程池的操作(线程池、调度器)private ExecutorService executorService;// 用于表示异步执行的结果private Future<String> future;// 可延迟或重复调用的线程池private ScheduledExecutorService scheduledExecutorService;// 一个延时、可接受计算结果private ScheduledFuture<String> scheduledFuture;/** * 使用Runnable创建Callable */@Testpublic void callableCreateTest() {// 使用Runnable、给定的返回值创建一个Callablecallable = Executors.callable(runnable, ExecutorsTest.class.getSimpleName());try {// 显示返回值System.out.println(callable.call());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 通过线程工厂创建线程 */@Testpublic void threadFactoryTest() {// 创建线程工厂threadFactory = Executors.defaultThreadFactory();// 创建一个Runnablerunnable = new RunnableConcrete();// 创建线程threadFactory.newThread(runnable).start();}/** * 产生根据需要而创建线程的线程池 当线程使用完后 可重复使用线程 */@Testpublic void executorServiceTest() {// 创建线程池executorService = Executors.newCachedThreadPool();// 在线程池中执行任务future = executorService.submit(runnable, "返回结果");System.out.println(future.isDone());// if(future.isDone()){try {// 获取任务的返回结果System.out.println(future.get());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/** * 调用任务集合 */@Testpublic void executorServiceCollectionsTest() {/* * CallableConcrete<String> callable=new CallableConcrete<String>(); * Collection<CallableConcrete<String>> * tasks=createCallableTasks(20,callable); */callable = new CallableConcrete<String>();// 构建集合任务Collection<Callable<String>> tasks = createCallableTasks(20, callable);// 创建线程池executorService = Executors.newCachedThreadPool();try {// 执行任务集合List<Future<String>> resuList = executorService.invokeAll(tasks);// 迭代任务集合iterator(resuList);// 关闭操作closeExecutorService(executorService);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 关闭线程池操作 * * @param executorService2 */private void closeExecutorService(ExecutorService executorService2) {// TODO Auto-generated method stubif (!executorService2.isShutdown()) {executorService2.shutdown();try {if (!executorService2.awaitTermination(10, TimeUnit.SECONDS)) {System.out.println("线程池未关闭");} else {System.out.println("线程池已成功关闭");}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/** * 迭代 * * @param <T> * @param resuList */@SuppressWarnings("unchecked")private <T> void iterator(Iterable<T> resuList) {// TODO Auto-generated method stubfor (T t : resuList) {try {System.out.println(((Future<String>) t).get());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/** * 创建可调度的任务 * * @return */private <E> Collection<E> createCallableTasks(int length, E e) {// TODO Auto-generated method stubCollection<E> list = new ArrayList<E>();for (int i = 0; i < length; i++) {list.add(e);}return list;}/** * 创建可延时的任务 */@Testpublic void scheduledExecutorServiceDelayTest() {// 获取可延时、重复调度的线程池scheduledExecutorService = Executors.newScheduledThreadPool(1);// 显示当前时间System.out.println(System.currentTimeMillis());// 延迟10s后 执行任务scheduledFuture = scheduledExecutorService.schedule(callable, 10,TimeUnit.SECONDS);try {// 获取线程池的执行任务的返回结果System.out.println(scheduledFuture.get() + "\t"+ System.currentTimeMillis());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 创建重复调度的任务 */@Testpublic void scheduledExecutorServiceTest() {// 获取可延时、重复调度的线程池scheduledExecutorService = Executors.newScheduledThreadPool(2);// 显示当前时间System.out.println(System.currentTimeMillis());// 延迟10s后 重复执行任务 scheduledFuture = (ScheduledFuture<String>) scheduledExecutorService.scheduleAtFixedRate(runnable, 10, 10,TimeUnit.SECONDS);//运行1分钟后 终止重复执行的任务scheduledExecutorService.schedule(new Runnable(){public void run() {// TODO Auto-generated method stub//终止重复执行的任务scheduledFuture.cancel(true);System.out.println("终止重复执行的任务");}}, 1*60, TimeUnit.SECONDS);// 获取线程池的执行任务的返回结果 因为任务被取消了 所以执行词句会报错try {System.out.println(scheduledFuture.get() + "\t"+ System.currentTimeMillis());} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch(CancellationException e){e.printStackTrace();}}}
结果
callableCreateTest()
mainRunnableConcreteExecutorsTest
threadFactoryTest()
pool-1-thread-1RunnableConcrete
executorServiceTest()
falsepool-1-thread-1RunnableConcrete返回结果
executorServiceCollectionsTest()
pool-1-thread-1CallableConcretepool-1-thread-2CallableConcretepool-1-thread-3CallableConcretepool-1-thread-2CallableConcretepool-1-thread-3CallableConcretepool-1-thread-1CallableConcretepool-1-thread-4CallableConcretepool-1-thread-1CallableConcretepool-1-thread-2CallableConcretepool-1-thread-3CallableConcretepool-1-thread-5CallableConcretepool-1-thread-2CallableConcretepool-1-thread-3CallableConcretepool-1-thread-4CallableConcretepool-1-thread-1CallableConcretepool-1-thread-6CallableConcretepool-1-thread-4CallableConcretepool-1-thread-5CallableConcretepool-1-thread-3CallableConcretepool-1-thread-2CallableConcrete线程池已成功关闭
scheduledExecutorServiceDelayTest()
1425202002086pool-1-thread-1CallableConcrete1425202012086
scheduledExecutorServiceTest()
1425202037535pool-1-thread-2RunnableConcretepool-1-thread-2RunnableConcretepool-1-thread-1RunnableConcretepool-1-thread-2RunnableConcretepool-1-thread-2RunnableConcretepool-1-thread-2RunnableConcrete终止重复执行的任务java.util.concurrent.CancellationExceptionat java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:203)at java.util.concurrent.FutureTask.get(FutureTask.java:80)at com.undergrowth.util.concurrent.ExecutorsTest.scheduledExecutorServiceTest(ExecutorsTest.java:237)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)at java.lang.reflect.Method.invoke(Method.java:585)at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99)at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81)at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:66)at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:38)at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
记录学习的脚步
0 0
- Runnable、Callable、Executor、ExecutorService、ScheduledExecutorService、Executors
- Future/FutureTask & Callable/Runnable & Executor/ExecutorService/Executors
- Executor、Executors、Callable、FutureTask、ExecutorService
- Java并发编程之Executor,Executors,ExecutorService,Future,Callable
- Executor,Executors,ExecutorService
- Runnable、Callable、Executor、Future
- Runnable、Callable、Executor、Future、FutureTask
- Executor, ExecutorService 和 Executors 间的不同
- Executor, ExecutorService 和 Executors 间的不同
- Executor, ExecutorService 和 Executors 间的不同
- Executor, ExecutorService 和 Executors 间的不同
- Executor, ExecutorService 和 Executors 间的不同
- Future,FutureTask,Executors,ExecutorService,Callable学习笔记
- JAVA多线程Callable、Executors -- ExecutorService简介
- Runnable、Callable、Executor、Future、FutureTask关系解读
- Callable、Runnable、Future、Executor的详细使用方法
- Runnable、Callable、Executor、Future、FutureTask关系解读
- Runnable、Callable、Executor、Future、FutureTask关系解读
- Head First JQuery学习笔记(二)
- PCB中Add layer 和 Plane 区别
- 04-3. 统计素数并求和
- HDU 2254解题报告
- 注册表禁用cmd
- Runnable、Callable、Executor、ExecutorService、ScheduledExecutorService、Executors
- 注册表全面禁用控制面板
- 运行tomcat7w.exe,提示:指定的服务未安装
- hdoj 1248 完全背包问题
- 黑马程序员——正则表达式
- 注册表中关闭组策略
- ios即时通讯客户端开发之-mac上安装MySQL
- poj 3045 Cow Acrobats
- Android系统回顾(二):Android基础知识