java - 从Thread返回值
我有一个HandlerThread的方法。值在Thread内更改,我想将其返回到test()方法。 有没有办法做到这一点?
public void test()
{
Thread uiThread = new HandlerThread("UIHandler"){
public synchronized void run(){
int value;
value = 2; //To be returned to test()
}
};
uiThread.start();
}
8个解决方案
59 votes
您可以使用本地最终变量数组。 变量必须是非基本类型,因此您可以使用数组。 您还需要同步两个线程,例如使用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.
}
};
ui