一直用java的线程,总感觉写起来阅读或书写起来不是方便,改进之。
实现类:
public class Task<R> {
private ExecutorService executorService = Executors.newCachedThreadPool();
Future<R> future;
private Supplier<R> fuc;
public boolean cannel() {
return future.cancel(true);
}
public Task(Supplier<R> fuc) {
this.fuc = fuc;
}
class InnerTask implements Callable<R> {
@Override
public R call() {
return fuc.get();
}
}
public void start() {
this.future = executorService.submit(new InnerTask());
executorService.shutdown();
}
public R result() throws ExecutionException, InterruptedException {
if (!future.isCancelled()) {
return future.get();
}
throw new InterruptedException();
}
使用示例:
//一个超时的计算
public Integer sum(List<Integer> list) {
Integer sum = 0;
for (Integer integer : list) {
sum += integer;
}
return sum;
}
public String getClassName() {
return getClass().getName();
}
@Test
public void testTask1() throws ExecutionException, InterruptedException {
List<Integer> list = Arrays.asList(1, 2, 3);
Task<Integer> task = new Task(() -> {
Integer sum = 0;
for (Integer integer : list) {
sum += integer;
}
return sum;
});
task.start();
//这里继续书写其它业务逻缉
String className = getClassName();
//计算结果
System.out.println(className + "运行结果是:" + String.valueOf(task.result()));
}
@Test
public void testTask2() throws ExecutionException, InterruptedException {
List<Integer> l = Arrays.asList(1, 2, 3);
Task<Integer> task = new Task(() -> {
return new BIPayTest().sum(l);
});
task.start();
//这里继续书写其它业务逻缉
String className = getClassName();
//计算结果
System.out.println(className + "运行结果是:" + String.valueOf(task.result()));
}