【问题标题】:How can I call interface callback on its caller thread?如何在其调用者线程上调用接口回调?
【发布时间】:2016-05-03 05:11:49
【问题描述】:

我有一个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 线程上获得结果的接口。当我像以下方法一样调用侦听器回调时,我在线程A 中得到结果:

            class A extend Thread {

            @Override
            public void run() {

                // do something in thread A.

                queryExecutorInterface.onPostExecute(cursor);
            }
          }

PS:我可以使用ReentrantLock 类而不是使用线程A 来解决这种情况。但由于我在此之上还有另一层,所以我不想使用锁定。

【问题讨论】:

    标签: java android multithreading


    【解决方案1】:

    您只需将另一个 Runnable 添加到 ThreadPool 中。所以你必须使 ThreadPool 成为 final:

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

    【讨论】:

    • 感谢您的回复。您的解决方案有一个问题,但它正在工作。如果我向threadPool 添加100 个任务,在获取数据后,我的新runnable 移动到threadPool queue 的末尾,是否有任何解决方案可以在threadPool 队列中运行这个runnable ASAP?
    • 你需要某种锁定。但这将阻塞池中的线程,直到响应到来。我建议你不要那样做。另一方面,您可以拥有两个独立的线程池。一个用于发送请求,另一个用于处理响应。
    • 我认为更好的方法是实现PriorityThreadPoolExecuter,如stackoverflow.com/questions/3545623/…。谢谢你的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    相关资源
    最近更新 更多