最好使用Android Executors。这是一些接口,它保留你的线程,而前一个被执行。
例如。你用户 10 线程可运行,(AsyncTask)。但是你明白,运行 10 个线程 - 这是个坏主意。因此,您只想为 3 个线程创建内存空间并节省设备性能。所以应该使用运行前三个线程的接口,并且!当某个线程被执行时,比你下一个运行。
更新!
因此,您只需添加所有线程(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 接口。因此,您需要阅读有关 java Thread 和 Runnable 接口以及 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