Java 如何在其调用线程上调用接口回调?

Java 如何在其调用线程上调用接口回调?,java,android,multithreading,Java,Android,Multithreading,我有一个ThreadPoolExecuter可以同时运行多个线程。在Runnable中,我想在另一个线程中运行方法,所以,我在execute方法中创建了另一个线程(线程A),现在我想得到线程A在executer线程中运行的结果。 让我用一个例子来澄清: ThreadPoolExecuter threadPool = Executors.newFixedThreadPool(5); threadPool.execute(new Runnable() { @Overrid

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

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
线程上获得结果的接口。由于我调用了侦听器回调,就像下面的方法一样,我在thread
A
中得到了结果:

            class A extend Thread {

            @Override
            public void run() {

                // do something in thread A.

                queryExecutorInterface.onPostExecute(cursor);
            }
          }

PS:我可以使用
ReentrantLock
类而不是使用Thread
A
来修复这个场景。但是,由于我在这上面还有一层,所以我不想使用锁定。

您只需要在线程池中添加另一个Runnable即可。因此,您必须使线程池成为最终版本:

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
                    }
                });
            }
        });   
    }
 });

谢谢你的回复。您的解决方案有一个问题,但正在运行。如果我将100个任务添加到
threadPool
,在获取数据后,我的新
runnable
移动到
threadPool队列的末尾
,是否有任何解决方案可以在
threadPool
队列中尽快运行此
runnable
。但这将阻止池中的线程,直到收到响应。我建议你不要那样做。另一方面,您可以有两个独立的线程池。一个用于发送请求,另一个用于处理响应。我认为更好的方法是实现
PriorityThreadPoolExecuter
like。谢谢你的回答