您可以使用本地最终变量数组。该变量需要是非原始类型的,所以你可以使用一个数组。您还需要使用CountDownLatch两个线程同步,例如:
public void test()
{
final CountDownLatch latch = new CountDownLatch(1);
final int[] value = new int[1];
Thread uiThread = new HandlerThread("UIHandler"){
@Override
public void run(){
value[0] = 2;
latch.countDown(); // Release await() in the test thread.
}
};
uiThread.start();
latch.await(); // Wait for countDown() in the UI thread. Or could uiThread.join();
// value[0] holds 2 at this point.
}
你也可以使用一个Executor
和Callable
这样的:
public void test() throws InterruptedException, ExecutionException
{
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() {
return 2;
}
};
Future<Integer> future = executor.submit(callable);
// future.get() returns 2 or raises an exception if the thread dies, so safer
executor.shutdown();
}
这是什么语言吗? – 2012-02-05 11:38:01
如果主线程必须等待处理线程在从方法返回之前完成,为什么首先使用处理线程呢? – 2012-02-05 11:43:14
@JBNizet我没有包含Thread实际所做的复杂性。它获得gps坐标,所以是的,我确实需要一个线程。 – Neeta 2012-02-05 11:59:26