我想运行一个持久的操作并能够看到它的以下阶段:
1) 尚未运行
2) 运行
3) 完成好了
4) 异常结束
我写了下面的代码,看起来过于复杂。它使用三个类:Work
、ThreadPoolExecutor
、FutureTask<?>
,其中Work
是手写的。
同时,工作是部分复制FutureTask<?>
功能(异常存储,这也是在内部完成的Future
,但在内部是封闭的)。
问题是:有没有几行方法可以从 Java、Groovy、GPars、Apache 等的预定义类中做同样的事情?
编码:
public class AsyncRunAndTrackState {
public static class Stub implements Runnable {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class Work implements Runnable {
private Exception exception;
private boolean active;
public synchronized Exception getException() {
return exception;
}
public synchronized void setException(Exception exception) {
this.exception = exception;
}
public synchronized boolean isActive() {
return active;
}
public synchronized void setActive(boolean active) {
this.active = active;
}
@Override
public final void run() {
setActive(true);
setException(null);
try {
runImpl();
}
catch (Exception e) {
setException(e);
}
finally {
setActive(false);
}
}
protected void runImpl() {
System.out.println("Before");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
throw new RuntimeException("Some exception occurred");
//System.out.println("After");
}
}
static ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
static FutureTask<?> future;
static Work work;
public static void main(String[] args) {
for(int i=0; i<10; ++i) {
executor.submit(new Stub());
}
work = new Work();
future = (FutureTask<?>) executor.submit(work);
while(true) {
System.out.println(String.format("future.done = %s, future.cancelled = %s", future.isDone(), future.isCancelled()));
System.out.println(String.format("work.active = %s, work.exception = %s", work.isActive(), work.getException()));
System.out.println();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}