本文是关于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;
/**
* 使用匿名类的方式构建可执行的任务
*/
@Test
public void testRun() {
// 匿名类
runnable = new Runnable() {
public void run() {
// TODO Auto-generated method stub
System.out.println("内部线程名:" + Thread.currentThread().getName());
System.out.println("内部线程输出:" + "发生什么");
}
};
// 执行任务
runnable.run();
System.out.println("外部线程名:" + Thread.currentThread().getName());
}
/**
* 使用单独的线程构建可执行的任务 注意 start()与run()的区别
*/
@Test
public void testThread() {
// 构建另外线程执行
thread = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
System.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 stub
System.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;
/**
* 使用调用者调用任务,同步执行
*/
@Test
public void synCallable() {
callable = new CallableConcrete<String>();
try {
System.out.println(callable.call());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 使用线程池进行任务调度
*/
@Test
public void asynCallable(){
callable = new CallableConcrete<String>();
try {
System.out.println(Executors.newCachedThreadPool().submit(callable).get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
}
}
/**
* Callable的实现类
*
* @author undergrowth
*
*/
class CallableConcrete<V> implements Callable<V> {
@SuppressWarnings("unchecked")
public V call() throws Exception {
// TODO Auto-generated method stub
return (V)(Thread.currentThread().getName()+"\t"+CallableConcrete.class.getSimpleName());
}
}
结果
syncCallable()
main CallableConcrete
pool-1-thread-1 CallableConcrete
可执行者
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 stub
System.out.println(Thread.currentThread().getName());
}
};
/**
* 测试异步执行
*/
@Test
public void asynExecuteTest() {
System.out.println(Thread.currentThread().getName());
executor = new AsynExecute();
executor.execute(runnable);
}
/**
* 测试同步执行
*/
@Test
public 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 stub
new Thread(command, "单独的线程").start();
}
}
/**
* 使用调用线程线程执行任务
* 同步执行的任务
* @author undergrowth
*
*/
class SyncExecute implements Executor {
public void execute(Runnable command) {
// TODO Auto-generated method stub
command.run();
}
}
结果
asynExecuteTest()
main
单独的线程
syncExecuteTest()
main
main
工厂类
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
*/
@Test
public void callableCreateTest() {
// 使用Runnable、给定的返回值创建一个Callable
callable = Executors.callable(runnable, ExecutorsTest.class
.getSimpleName());
try {
// 显示返回值
System.out.println(callable.call());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 通过线程工厂创建线程
*/
@Test
public void threadFactoryTest() {
// 创建线程工厂
threadFactory = Executors.defaultThreadFactory();
// 创建一个Runnable
runnable = new RunnableConcrete();
// 创建线程
threadFactory.newThread(runnable).start();
}
/**
* 产生根据需要而创建线程的线程池 当线程使用完后 可重复使用线程
*/
@Test
public 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 block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 调用任务集合
*/
@Test
public 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 block
e.printStackTrace();
}
}
/**
* 关闭线程池操作
*
* @param executorService2
*/
private void closeExecutorService(ExecutorService executorService2) {
// TODO Auto-generated method stub
if (!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 block
e.printStackTrace();
}
}
}
/**
* 迭代
*
* @param <T>
* @param resuList
*/
@SuppressWarnings("unchecked")
private <T> void iterator(Iterable<T> resuList) {
// TODO Auto-generated method stub
for (T t : resuList) {
try {
System.out.println(((Future<String>) t).get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 创建可调度的任务
*
* @return
*/
private <E> Collection<E> createCallableTasks(int length, E e) {
// TODO Auto-generated method stub
Collection<E> list = new ArrayList<E>();
for (int i = 0; i < length; i++) {
list.add(e);
}
return list;
}
/**
* 创建可延时的任务
*/
@Test
public 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 block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 创建重复调度的任务
*/
@Test
public 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 block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(CancellationException e){
e.printStackTrace();
}
}
}
结果
callableCreateTest()
main RunnableConcrete
ExecutorsTest
threadFactoryTest()
pool-1-thread-1 RunnableConcrete
executorServiceTest()
false
pool-1-thread-1 RunnableConcrete
返回结果
executorServiceCollectionsTest()
pool-1-thread-1 CallableConcrete
pool-1-thread-2 CallableConcrete
pool-1-thread-3 CallableConcrete
pool-1-thread-2 CallableConcrete
pool-1-thread-3 CallableConcrete
pool-1-thread-1 CallableConcrete
pool-1-thread-4 CallableConcrete
pool-1-thread-1 CallableConcrete
pool-1-thread-2 CallableConcrete
pool-1-thread-3 CallableConcrete
pool-1-thread-5 CallableConcrete
pool-1-thread-2 CallableConcrete
pool-1-thread-3 CallableConcrete
pool-1-thread-4 CallableConcrete
pool-1-thread-1 CallableConcrete
pool-1-thread-6 CallableConcrete
pool-1-thread-4 CallableConcrete
pool-1-thread-5 CallableConcrete
pool-1-thread-3 CallableConcrete
pool-1-thread-2 CallableConcrete
线程池已成功关闭
scheduledExecutorServiceDelayTest()
1425202002086
pool-1-thread-1 CallableConcrete 1425202012086
scheduledExecutorServiceTest()
1425202037535
pool-1-thread-2 RunnableConcrete
pool-1-thread-2 RunnableConcrete
pool-1-thread-1 RunnableConcrete
pool-1-thread-2 RunnableConcrete
pool-1-thread-2 RunnableConcrete
pool-1-thread-2 RunnableConcrete
终止重复执行的任务
java.util.concurrent.CancellationException
at 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)
记录学习的脚步