android 中主线程和工作线程之间的通信
Communication between main thread and worker threads in android
在我的第一个 android 项目中,我做了一些数据操作,所以我使用多线程方法。
在 MainActivity 中,我创建了多个 Runnable 对象并使用 ExecutorService 运行 所有线程。按照我的理解,所有的线程都放在消息队列中,依次执行。并且因为主线程已经在队列中,它会在启动其他线程之前执行。有什么方法可以让主线程等待其他线程完成然后继续吗?
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//call MyFunction here
}
private List<Pair[]> myFunction(int dataInput) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(12);
MyTask MyTask = new MyTask();
for (int i = 0; i < gallerySize; ++i) {
final int index = i;
Runnable runnable = MyTask.runLongOperationWithThread(new MyTask.DataCallback(){
@Override
public void onSuccess(double[] scores) {
// get data back to main thread
}
@Override
public void onError(Exception ex) {
//TODO: log this error out to file
}
});
executorService.execute(runnable);
}
// try to get back all data from multi threading and do some operations
return returnList;
}
在这种情况下,Looper 和 Handler 有帮助吗?
如果我对android概念和线程有任何误解,请指正。
谢谢。
在 Android 中,停止主线程是 气馁的 。系统会告诉用户应用程序没有响应。但是,您可以 "notify" 后台线程完成其工作的主线程。一旦主线程知道这一点,它就会做一些事情。常见于Android,就是AsyncTask的意思。
然而,AsyncTask
用于简单的一个线程。对于您的情况,解决方案之一是组合 ExecutorService
和 AsyncTask
。在您创建的 AsyncTask
实例的 doInBackground
方法中,像往常一样使用 ExecutorService
,并等待它在 shutdown(); awaitTermination()
或 invokeAll()
之前完成。阅读 this question/answer 了解有关如何等待 ExecutorService
完成的更多信息。
private class WrappingTask extends AsyncTask<Void, Void, Exception> {
protected Exception doInBackground(Void... args) {
ExecutorService taskExecutor = Executors.newFixedThreadPool(12);
for (. . .) {
taskExecutor.execute(new MyTask(. . .));
}
taskExecutor.shutdown();
try {
taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
. . .
return e;
}
return null;
}
protected void onPostExecute(Exception error) {
// Notify the user that the task has finished or do anything else
// and handle error
}
}
长时间运行宁任务
AsyncTask
是一个方便的 class 使线程和通信(到主线程)更容易。 long 运行ning任务的问题是用户可以离开Activity
(然后再来),或者有来电等等,如果你不处理这个Activity lifecycle 小心,就是这样"dangerous",AsyncTask
不处理这个。
长 运行ning 任务应该是 运行 中的一个 Service
. Note that Service
is also run in the main thread, so the approach would be the same, unless you use IntentService
。在 IntentService
的情况下,只需执行 onHandleIntent
方法中的所有线程(以前在 doInBackground
中)并在那里等待,此方法在工作线程上调用。
与 Activity
通信 Service
并在其生命周期中保持 Activity
状态的一致性是一个漫长的故事。您最好边喝咖啡边阅读 "a full concentration" 中的文档 :D。这可能会有所帮助:
在我的第一个 android 项目中,我做了一些数据操作,所以我使用多线程方法。
在 MainActivity 中,我创建了多个 Runnable 对象并使用 ExecutorService 运行 所有线程。按照我的理解,所有的线程都放在消息队列中,依次执行。并且因为主线程已经在队列中,它会在启动其他线程之前执行。有什么方法可以让主线程等待其他线程完成然后继续吗?
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//call MyFunction here
}
private List<Pair[]> myFunction(int dataInput) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(12);
MyTask MyTask = new MyTask();
for (int i = 0; i < gallerySize; ++i) {
final int index = i;
Runnable runnable = MyTask.runLongOperationWithThread(new MyTask.DataCallback(){
@Override
public void onSuccess(double[] scores) {
// get data back to main thread
}
@Override
public void onError(Exception ex) {
//TODO: log this error out to file
}
});
executorService.execute(runnable);
}
// try to get back all data from multi threading and do some operations
return returnList;
}
在这种情况下,Looper 和 Handler 有帮助吗?
如果我对android概念和线程有任何误解,请指正。
谢谢。
在 Android 中,停止主线程是 气馁的 。系统会告诉用户应用程序没有响应。但是,您可以 "notify" 后台线程完成其工作的主线程。一旦主线程知道这一点,它就会做一些事情。常见于Android,就是AsyncTask的意思。
然而,AsyncTask
用于简单的一个线程。对于您的情况,解决方案之一是组合 ExecutorService
和 AsyncTask
。在您创建的 AsyncTask
实例的 doInBackground
方法中,像往常一样使用 ExecutorService
,并等待它在 shutdown(); awaitTermination()
或 invokeAll()
之前完成。阅读 this question/answer 了解有关如何等待 ExecutorService
完成的更多信息。
private class WrappingTask extends AsyncTask<Void, Void, Exception> {
protected Exception doInBackground(Void... args) {
ExecutorService taskExecutor = Executors.newFixedThreadPool(12);
for (. . .) {
taskExecutor.execute(new MyTask(. . .));
}
taskExecutor.shutdown();
try {
taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
. . .
return e;
}
return null;
}
protected void onPostExecute(Exception error) {
// Notify the user that the task has finished or do anything else
// and handle error
}
}
长时间运行宁任务
AsyncTask
是一个方便的 class 使线程和通信(到主线程)更容易。 long 运行ning任务的问题是用户可以离开Activity
(然后再来),或者有来电等等,如果你不处理这个Activity lifecycle 小心,就是这样"dangerous",AsyncTask
不处理这个。
长 运行ning 任务应该是 运行 中的一个 Service
. Note that Service
is also run in the main thread, so the approach would be the same, unless you use IntentService
。在 IntentService
的情况下,只需执行 onHandleIntent
方法中的所有线程(以前在 doInBackground
中)并在那里等待,此方法在工作线程上调用。
与 Activity
通信 Service
并在其生命周期中保持 Activity
状态的一致性是一个漫长的故事。您最好边喝咖啡边阅读 "a full concentration" 中的文档 :D。这可能会有所帮助: