gpt4 book ai didi

java - 如何在其调用者线程上调用接口(interface)回调?

转载 作者:太空狗 更新时间:2023-10-29 13:59:27 26 4
gpt4 key购买 nike

我有一个 ThreadPoolExecuter 可以同时运行多个线程。在 Runnable 中,我想在另一个线程中运行方法,所以我在执行方法中创建了另一个线程(线程 A),现在我想获取线程 A 的结果以在执行程序线程中运行。让我用一个例子来澄清:

ThreadPoolExecuter threadPool = Executors.newFixedThreadPool(5);

threadPool.execute(new Runnable() {
@Override
public void run() {

// do something in threadPool thread

// call method in thread A
getInfo(new QueryExecutorInterface() {
@Override
public void onPostExecute(Cursor cursor) {

// do other thing in threadPool thread again.

}
});
}
});

QueryExecutorInterface 是我想要传递给线程 A 并在 ThreadPool 线程上获取结果的接口(interface)。当我像下面的方法一样调用监听器回调时,我在线程 A 中得到结果:

            class A extend Thread {

@Override
public void run() {

// do something in thread A.

queryExecutorInterface.onPostExecute(cursor);
}
}

PS:我可以使用 ReentrantLock 类而不是使用 Thread A 来解决这个问题。但是因为我在这之上还有另一层,所以我不想使用锁定。

最佳答案

您只需要将另一个 Runnable 添加到 ThreadPool 中即可。所以你必须让 ThreadPool 成为最终的:

final ThreadPoolExecuter threadPool = Executors.newFixedThreadPool(5); // note the final modifier

threadPool.execute(new Runnable() {
@Override
public void run() {

// do something in threadPool thread
// call method in thread A
getInfo(new QueryExecutorInterface() {
@Override
public void onPostExecute(Cursor cursor) {
threadPool.execute(new Runnable() { // adding another callback so it runs in threadpool
@Override
public void run() {
// do the thing here
}
});
}
});
}
});

关于java - 如何在其调用者线程上调用接口(interface)回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36996050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com