我实现了一个 Runnable,如果 boolean 值变为 true,它会检查正确性。
但我想将此值返回到我启动线程的类。
我注意到我可以使用 Future Callables 返回一个值,使用它们我可以计算一些东西并立即返回它,但我无法永久检查该值是否变为 true。
我怎样才能实现这个目标?
感谢您的帮助。
public class ResultChecker implements Runnable{
private DrawView drawView;
public ResultChecker(DrawView drawView){
this.drawView = drawView;
}
public void run() {
boolean run = true;
while(run){
if(drawView.isNextQuestion()){
//RETURN VALUE HERE
run = false;
}
}
}
}
最佳答案
如果您想要轮询,请在 ResultChecker
中创建一个方法,该方法可以由需要返回值的线程调用。
public class ResultChecker implements Runnable{
private DrawView drawView;
private volatile Result r;
public ResultChecker(DrawView drawView){
this.drawView = drawView;
this.r = null;
}
public Result poll() {
return r;
}
public void run() {
boolean run = true;
while(run){
if(drawView.isNextQuestion()){
//RETURN VALUE HERE
r = someObject;
// once r has been assigned, you cannot touch it again
// or the object it refers to from this thread because
// there are no locks
run = false;
}
}
}
}
轮询器将像这样轮询:
r = resultChecker.poll();
if(r != null) {
// we have result
} else {
// result is not ready
// try again later
}
如果您想返回多个值,则必须使用队列对其进行扩展。
关于java - 线程返回值永久检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8735412/