您可以使用本地最終變量數組。該變量需要是非原始類型的,所以你可以使用一個數組。您還需要使用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