如果您只需要从另一个线程轮询结果,请尝试使用@Piotr建议的java.util.concurrent包。以下是如何执行此操作的具体示例:
import java.util.concurrent.*;
class Main{
public static void main(String[] args) throws Exception{
//Create a service for executing tasks in a separate thread
ExecutorService ex = Executors.newSingleThreadExecutor();
//Submit a task with Integer return value to the service
Future otherThread = ex.submit(new Callable(){
public Integer call(){
//do you main logic here
return 999;//return the desired result
}
}
//you can do other stuff here (the main thread)
//independently of the main logic (in a separate thread)
//This will poll for the result from the main
//logic and put it into "result" when it's available
Integer result = otherTread.get();
//whatever you wanna do with your result
}
}希望这可以帮助。