1.在我的android应用程序中,有超过10个Asynctask可用。
2.它用于从服务器获取数据到本地数据库。
我将异步任务保留在单独的类中。
那么我可以像下面提到的那样同时调用吗?在同步和插入本地数据库时,它会产生任何问题,或者建议我任何其他解决方案。
我的代码:
if (isInternetPresent)
{
new AsyncTaskSync_MappingTableClass1(MainActivity.this).execute();
new AsyncTaskSync_MappingTableClass2(MainActivity.this).execute();
new AsyncTaskSync_MappingTableClass3(MainActivity.this).execute();
new AsyncTaskSync_MappingTableClass4(MainActivity.this).execute();
}
else
{
Log.i("INFO"," No Internet.. :-(");
}
最佳答案
最好使用Android Executors 。这是一些接口(interface),可以在执行前一个线程时保留您的线程。
例如。您使用 10 个可运行线程 (AsyncTask)。但你知道,运行 10 个线程 - 这是个坏主意。因此您只想为 3 个线程创建内存空间并节省设备性能。因此应该使用运行前三个线程的接口(interface),并且!当执行某个线程时,接下来运行。
更新! 因此,您只需添加所有线程(10、100 ....),执行器就会正确管理内存中的所有任务。还有另一个构造函数 TheadPool。检查文档以获取更多信息。干杯!
示例:
List<AsyncTask> listTask = new ArrayList<>();
....
//Add all your runnables interfaces
Executor ex = ThreadPoolExecutor.newFixedThreadPool(3);
//Number of active threads - 3
for (int i = 10; i < 10; i++) {
ex.execute(listTask.get(i));
}
另一个例子: 老实说,AsyncTask 它不是后台工作的最佳解决方案。所以executor支持Runnable接口(interface)。因此,您需要阅读有关 java Thread 和 Runnable 接口(interface)以及 android Executors 的信息,这将是每次的最佳解决方案。在使用Retrofit、RxJava、Volley等实现。但java原生方法最简单、稳定。
最后更新! 请访问this resource, to read more .
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleThreadPool extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main)
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread(String.valueOf(i));
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println('Finished all threads');
}
}
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s){
this.command=s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+' Start. Command = '+command);
processCommand();
System.out.println(Thread.currentThread().getName()+' End.');
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString(){
return this.command;
}
}
结果之前的代码。
pool-1-thread-2 Start. Command = 1
pool-1-thread-4 Start. Command = 3
pool-1-thread-1 Start. Command = 0
pool-1-thread-3 Start. Command = 2
pool-1-thread-5 Start. Command = 4
pool-1-thread-4 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-3 Start. Command = 8
pool-1-thread-2 End.
pool-1-thread-2 Start. Command = 9
pool-1-thread-1 Start. Command = 7
pool-1-thread-5 Start. Command = 6
pool-1-thread-4 Start. Command = 5
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-3 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
Finished all threads
关于android - 在android中调用多个异步任务从服务器获取数据到本地的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36473942/