【发布时间】:2014-10-27 10:40:31
【问题描述】:
起初,我使用 Runnable 并构建了一个“while(true)”循环来继续处理我的工作。 现在我在改用 Callable 时发现了一些困难。
package com;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableAndFuture {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ChildCallbale childCallbale = new ChildCallbale();
FutureTask<Integer> future = new FutureTask<Integer>(childCallbale);
Thread thread = new Thread(future);
thread.start();
childCallbale.setVar(1);
System.out.println(future.get());
childCallbale.setVar(2);
System.out.println(future.get());
}
}
class ChildCallbale implements Callable<Integer>{
private int var;
public void setVar(int var){
this.var = var;
}
@Override
public Integer call() throws Exception {
Thread.sleep(2000);
return var;
}
}
如您所见,我希望得到不同的结果。不幸的是,2 个结果等于 1。 我不仅想知道如何实现我的要求,我还想知道我的代码不正确的原因。提前致谢。
【问题讨论】:
-
简单地说,你的基本概念都错了。你需要通过学习这些重新开始。
标签: java multithreading variables callable