简体   繁体   中英

AsyncTask doesn't run simultaneously with second AsyncTask

i have an 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

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. 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 :

Starting with HONEYCOMB , tasks are executed on a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR .

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

Use executeOnExecutor with THREAD_POOL_EXECUTOR .

Since API 11, AsyncTask s don't run parallel by default. You need to call executeOnExecutor with given param to make sure the AsyncTasks run parallel.

You can construct something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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