gpt4 book ai didi

java - 为什么 ExecutorService 没有被频繁执行

转载 作者:行者123 更新时间:2023-12-01 14:20:44 26 4
gpt4 key购买 nike

有一个方法我需要在每个特定时间频繁更新,所以我正在测试 java ExecutorService ,但我的方法没有经常更新,你能告诉我为什么吗?

这些是我的类(class)

FutureTask.java

package com;

import java.lang.reflect.Method;
import java.util.concurrent.*;

public class FutureTask {
private static ExecutorService executor = Executors.newCachedThreadPool();
private static FutureTask _instance = new FutureTask();

public static FutureTask getInstance() {
return _instance;
}

private static int timoutsec = 15;

public Object submiteTask(final Object obj, final Method method,
final Object[] params) throws Exception {
return submiteTask(obj, method, params, -1);
}

public Object submiteTask(final Object obj, final Method method,
final Object[] params, int timeoutSeconds) throws Exception {
if (null != obj && method != null) {
Callable<Object> task = new Callable<Object>() {
public Object call() {
try {
method.setAccessible(true);
Object resultObj = method.invoke(obj, params);
return resultObj;
} catch (Exception e) {
}
return null;
}
};
Future<Object> future = executor.submit(task);
try {
Object result = null;
if (timeoutSeconds < 0) {
result = future.get(timoutsec, TimeUnit.SECONDS);
} else {
result = future.get(timeoutSeconds, TimeUnit.SECONDS);
}
return result;
} catch (TimeoutException e) {
} catch (Exception e) {
} finally {
future.cancel(true);
}
}
return null;
}

public static void main(String args[]) {
try {
FutureTask.getInstance().submiteTask(
new TestingFutureTaskUtil(),
TestingFutureTaskUtil.class.getDeclaredMethod(
"updateMethodCalled",
new Class<?>[] { String.class }),
new Object[] { "UBSC!OC1010" }, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
}

TestingFutureTaskUtil.java

package com;

public class TestingFutureTaskUtil {

public void updateMethodCalled(String symbol) {

System.out.println("updateMethodCalled" + symbol);

}

}

提前致谢。

最佳答案

您只提交一项作业,因此 updateMethodCalled 仅被调用一次。

关于java - 为什么 ExecutorService 没有被频繁执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17593634/

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