gpt4 book ai didi

java - 异步运行方法并能够查看其状态的最简单方法是什么?

转载 作者:行者123 更新时间:2023-12-01 10:45:30 24 4
gpt4 key购买 nike

我想运行一个持久的操作并能够看到它的以下阶段:

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();
}

}

}
}

最佳答案

我通常使用数据流队列来通知异步 Activity 的状态更改。

关于java - 异步运行方法并能够查看其状态的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34209301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com