1

我创建了空白项目并尝试执行下一个代码。不幸的是,我遇到了问题:在未完成我的线程时未加载主要活动。如果不使用线程的返回值一切正常。不幸的是最终的 ExecutorService 服务;最终的未来任务;

    service = Executors.newFixedThreadPool(1);
    task    = service.submit(new Foo());


    try
    {
        final String str;

        // waits the 10 seconds for the Callable.call to finish.
        str = task.get();
        Log.d("VSK",str);
    }
    catch(final InterruptedException ex)
    {
        ex.printStackTrace();
    }
    catch(final ExecutionException ex)
    {
        ex.printStackTrace();
    }

    service.shutdownNow();

}
class Foo
        implements Callable<String>
{
    public String call()
    {
        try
        {
            // sleep for 10 seconds
            Thread.sleep(10 * 1000);
        }
        catch(final InterruptedException ex)
        {
            ex.printStackTrace();
        }

        return ("Hello, World!");
    }
}
4

1 回答 1

2

str = task.get();当您的可调用对象在其他线程中执行时,此行会阻塞 main thead。通过Handler从您的任务返回结果或使用AsyncTask

于 2013-01-16T10:31:39.843 回答