gpt4 book ai didi

android - AsyncTask 不会与第二个 AsyncTask 同时运行

转载 作者:行者123 更新时间:2023-11-29 14:50:49 29 4
gpt4 key购买 nike

我有一个异步任务

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

如果我尝试通过调用生成两个 LoadData

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

我期望输出:

Downloading Downloading Downloaded Downloaded

但是我得到了

Downloading Downloaded Downloading Downloaded

这意味着 AsyncTask 不会同时执行。为什么是这样?我认为线程的意义在于不会发生这种情况? + 有没有办法让它们同时运行而无需更改太多代码?

最佳答案

根据 AsyncTask documentation执行顺序下:

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.

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

关于android - AsyncTask 不会与第二个 AsyncTask 同时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18581152/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com