我有一个带有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();
}
发布于 2012-02-05 19:51:32
您可以使用局部最终变量数组。该变量需要是非基元类型,因此可以使用数组。您还需要同步这两个线程,例如使用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.
}
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 19:46:36
您正在寻找的可能是代替Runnable
的Callable<V>
接口,并使用Future<V>
对象检索值,该对象也允许您等待直到计算出值为止。您可以通过从Executors.newSingleThreadExecutor()
获得的ExecutorService
来实现此目的。
public void test() {
int x;
ExecutorService es = Executors.newSingleThreadExecutor();
Future<Integer> result = es.submit(new Callable<Integer>() {
public Integer call() throws Exception {
// the other thread
return 2;
}
});
try {
x = result.get();
} catch (Exception e) {
// failed
}
es.shutdown();
}
发布于 2018-02-23 18:13:10
从Java8开始,我们有了CompletableFuture
。就您的情况而言,您可以使用supplyAsync
方法在执行后获取结果。
请找到一些参考here。
CompletableFuture<Integer> completableFuture
= CompletableFuture.supplyAsync(() -> yourMethod());
completableFuture.get() //gives you the value
https://stackoverflow.com/questions/9148899
复制相似问题