简体   繁体   English

ExecutorService似乎在UI上运行线程?

[英]ExecutorService seems to be running thread on The UI?

Iam attempting to use ExecutorService to run some code to connect my client to a server. Iam尝试使用ExecutorService运行一些代码将我的客户端连接到服务器。 Obviously Iam trying to get this to run on a seperate thread to the UI Thread, But my UI freezes when the code is executing.Which is not what I was excpecting. 显然Iam试图让它在一个单独的线程上运行到UI线程,但是我的UI在代码执行时冻结。这不是我想要的。 I thought ExecutorService would run on a seperate thread? 我以为ExecutorService会在一个单独的线程上运行? below is my code 下面是我的代码

@Override
public void registerDevice() {


    ExecutorService exservice = Executors.newFixedThreadPool(10);
    Future<Boolean> future = exservice.submit(new Callable() {

        @Override
        public Boolean call() throws Exception {

        android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

            try {
                Thread.sleep(20000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            reghandler.post(new Runnable() {
                @Override
                public void run() {
                    regpresenter.updateUIProgress();
                }
            });


            return true;
        }
    });

    exservice.shutdown();
    try {
        Boolean done = future.get(10, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (TimeoutException e) {
        e.printStackTrace();
        warningstr = "Server call timed out!";
    }
   exservice.shutDownNow();

}

If anyone can tell my why this doesnt run seperate to the UI thread I would be grateful. 如果有人能告诉我为什么这不会分开运行到UI线程,我将不胜感激。 Maybe there is something Iam missing after reading all the docs on executor service. 在阅读有关执行者服务的所有文档后,也许有些东西缺失了。 also I have another solution that seems to work but it creates a circular dependency with a timertask within my run method of another thread. 我还有另一个似乎有效的解决方案,但它在另一个线程的run方法中创建了一个带有timertask的循环依赖。 The timertask interrupts the thread after timeout, if The thread is alive. 如果线程处于活动状态,则timertask会在超时后中断线程。 so I dont really want to use that solution. 所以我真的不想使用那个解决方案。 Also iam just testing the timeout works at present. 我也只是测试当前的超时工作。 Ive left out some of the code in the method as its not really relevant to my issue. 我遗漏了方法中的一些代码,因为它与我的问题不太相关。 Thanks again 再次感谢

Below code means to wait to task result (maximum with 10 seconds timeout) 下面的代码表示等待任务结果(最大值为10秒超时)

Boolean done = future.get(10, TimeUnit.SECONDS);

if you don't want to wait till task is completed, don't call get(). 如果您不想等到任务完成,请不要调用get()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM