gpt4 book ai didi

java - Java 中的内部 FutureTask

转载 作者:行者123 更新时间:2023-12-02 05:01:14 24 4
gpt4 key购买 nike

我尝试实现一个内部方法,以便在新线程中执行以下代码

MyPojo result = null;
final MyPojo result2 = result;

FutureTask<MyPojo> runnableTask = new FutureTask<MyPojo>(
new Runnable() {

BindJSON<MyPojo> binding;

// Make the URL at which the product list is found
String sourceURLString =
"http://www.....ca/files/{CAT_ID}.json";

@Override
public void run() {
sourceURLString = sourceURLString.replace("{CAT_ID}", catId);
binding = new BindJSON<MyPojo>();
result2 = binding.downloadData(sourceURLString, MyPojo.class);
}
},
result2);

runnableTask.run();

所以,现在我收到一个错误:无法分配最终局部变量 result2,因为它是在封闭类型中定义的。我看一下这个答案:Cannot refer to a non-final variable i inside an inner class defined in a different method但这对我不起作用。我应该做什么才能使这项工作成功?

最佳答案

您可能想使用 Callable ,不是 Runnable:

// the variable holding the result of a computation
String result = null;

FutureTask<String> runnableTask = new FutureTask<String>(
new Callable<String>() {
public String call() throws Exception {
// (asynchronous) computation ...
return "42";
}
});

System.out.println("result=" + result); // result=null

// this will invoke call, but it will all happen in the *same thread*
runnableTask.run();

// to have a parallel thread execute in the 'background'
// you can use java.util.concurrent.Executors
// Note: an ExecutorService should be .shutdown() properly
// Executors.newSingleThreadExecutor().submit(runnableTask);

// waits for the result to be available
result = runnableTask.get();

// you can also add timeouts:
// result = runnableTask.get(100, TimeUnit.MILLISECONDS);

System.out.println("result=" + result); // result=42

关于java - Java 中的内部 FutureTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13841096/

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