程序的方法中有一個 HandlerThread。在線程中改變了一個值,然後我想把它返回到 test()方法。有什麼方法能實現呢?
public void test()
{
Thread uiThread = new HandlerThread("UIHandler"){
public synchronized void run(){
int value;
value = 2; //To be returned to test()
}
};
uiThread.start();
}
你可以使用一個本地的 final 變量,變量需要是 non-primitive 類型,所以你可以使用一個數組。也需要同步兩個線程,例如使用一個 CountDownLatch:
public void test()
{
final CountDownLatch latch = new CountDownLatch(1);
final int[] value = new int[1];
Thread uiThread = new HandlerThread("UIHandler"){
@Override
public synchronized void run(){
value[0] = 2;
latch.countDown(); // Release await() in the test thread.
}
};
uiThread.start();
latch.await(); // Wait for countDown() in the UI thread.
// 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
executor.shutdown();
}