简体   繁体   English

AsyncTask不能与第二个AsyncTask同时运行

[英]AsyncTask doesn't run simultaneously with second AsyncTask

i have an AsyncTask 我有一个AsyncTask

private class LoadData extends AsyncTask<String, Void, String> {
    private String WEBURL;
    LoadData(String url){
        this.WEBURL=url;
    }
    protected String doInBackground(String... params) {
        System.out.println("Downloading");
        URL url = new URL(WEBURL);
        URLConnection conn = url.openConnection();
        conn.connect();
        byte buffer[] = new byte[1024];
        InputStream in = new BufferedInputStream(url.openStream());
        String contents="";
        while((count = in.read(buffer))!=-1){
        total+=count;
        contents += new String(buffer, 0, count);
        }
        System.out.println("Downloaded");
        in.close;
    }
}

If i try to make two LoadData 's by calling 如果我尝试通过调用两个LoadData

new LoadData("http://www.google.com").execute();
new LoadData("http://www.stackoverflow.com").execute();

I would expect output: 我期望输出:

Downloading Downloading Downloaded Downloaded 正在下载正在下载已下载已下载

But instead i get 但是我得到了

Downloading Downloaded Downloading Downloaded 正在下载已下载正在下载已下载

Which means that the AsyncTask s are not executing simultaneously. 这意味着AsyncTask不会同时执行。 Why is this? 为什么是这样? I thought the point of threading was that this wouldn't happen? 我以为穿线的重点是这不会发生吗? + is there a way i can make them run simultaneously without changing too much code? +有没有一种方法可以使它们同时运行而无需更改太多代码?

Per the AsyncTask documentation under Order of Execution : 根据执行顺序下的AsyncTask文档

Starting with HONEYCOMB , tasks are executed on a single thread to avoid common application errors caused by parallel execution. HONEYCOMB开始,任务在单个线程上执行,以避免由并行执行引起的常见应用程序错误。 If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR . 如果您确实想要并行执行,则可以使用THREAD_POOL_EXECUTOR调用executeOnExecutor(java.util.concurrent.Executor, Object[])

Ie, new LoadData("http://www.google.com").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); 即, new LoadData("http://www.google.com").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

Use executeOnExecutor with THREAD_POOL_EXECUTOR . executeOnExecutorTHREAD_POOL_EXECUTOR一起THREAD_POOL_EXECUTOR

Since API 11, AsyncTask s don't run parallel by default. 从API 11开始,默认情况下AsyncTask不会并行运行。 You need to call executeOnExecutor with given param to make sure the AsyncTasks run parallel. 您需要使用给定的参数调用executeOnExecutor ,以确保AsyncTasks并行运行。

You can construct something like 您可以构造类似

if (Build.Version.SDK_INT >= 11){
    myAsyncTask.executeOnExecutor(...);
}else{
    myAsyncTask.execute(...);
}

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

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