版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014070705/article/details/81915514
public class SingleExecutor {
private ScheduledExecutorService executor = Executors
.newSingleThreadScheduledExecutor();
private CopyOnWriteArrayList<Future<?>> taskFutures = new CopyOnWriteArrayList<>();
public SingleExecutor() {
}
public <T> Future<T> submit(Callable<T> callable) {
Future<T> future = executor.submit(callable);
taskFutures.add(future);
return future;
}
public <T> ScheduledFuture<T> schedule(Callable<T> callable, long delay,
TimeUnit unit) {
ScheduledFuture<T> future = executor.schedule(callable, delay, unit);
taskFutures.add(future);
return future;
}
public boolean isShutdown() {
return executor.isShutdown();
}
public boolean isTerminated() {
return executor.isTerminated();
}
public void shutdown() {
shutdownNow();
}
public List<Runnable> shutdownNow() {
LogX.d("#shutdownNow");
cancelAll();
return executor.shutdownNow();
}
public void cancelAll() {
for (Future<?> future : taskFutures) {
if (future != null && !future.isDone() && !future.isCancelled()) {
future.cancel(true);
taskFutures.remove(future);
}
}
}
public Future<?> submit(Runnable task) {
Future<?> future = executor.submit(task);
taskFutures.add(future);
return future;
}
public <T> Future<T> submit(Runnable task, T result) {
Future<T> future = executor.submit(task, result);
taskFutures.add(future);
return future;
}
public void execute(Runnable command) {
executor.execute(command);
}
public ScheduledFuture<?> schedule(Runnable command, long delay,
TimeUnit unit) {
ScheduledFuture<?> future = executor.schedule(command, delay, unit);
taskFutures.add(future);
return future;
}
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
ScheduledFuture<?> future = executor.scheduleAtFixedRate(command, initialDelay, period, unit);
taskFutures.add(future);
return future;
}
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
long initialDelay, long delay, TimeUnit unit) {
ScheduledFuture<?> future = executor.scheduleWithFixedDelay(command, initialDelay, delay,
unit);
taskFutures.add(future);
return future;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
shutdownNow();
executor = null;
}
}