[英]Where does a method call from a thread run?
This is the code I wish to write这是我想写的代码
void longRunningMethod() {
new Thread(new Runnable() {
@Override
public void run() {
//a time consuming task
updateUi();
}
}).start();
}
public void updateUi(){
Collections.sort(playerArrayList, Collections.reverseOrder(new Comparator<Player>() {
@Override
public int compare(Player p1, Player p2) {
return Integer.valueOf(p1.getScore()).compareTo(p2.getScore());
}
}));
adapter.notifyDataSetChanged();
//some more code here
}
Firstly : When I call updateUi() from thread, will it run on the thread from where it was called (ie thread of longRunningMethod() ) or will it run in the main thread?首先:当我从线程调用 updateUi() 时,它会在调用它的线程上运行(即 longRunningMethod() 的线程)还是在主线程中运行?
Secondly : as in the code, I am sorting an arraylist of custom objects, Is it safe to run it in the main thread?其次:在代码中,我正在对自定义对象的 arraylist 进行排序,在主线程中运行它安全吗? Or should I use another thread?或者我应该使用另一个线程?
I know that about task implementation with completion Listener but I want to run the updateUi method on different thread just to be on safer side.我知道关于完成监听器的任务实现,但我想在不同的线程上运行 updateUi 方法只是为了更安全。
Any action performed within a thread, including the methods you call, will still be executed in the running thread, and not in the Main thread.在线程中执行的任何操作,包括您调用的方法,仍将在运行线程中执行,而不是在主线程中执行。 Therefore the way you are implementing your updateUI method will make it to still run within the executing thread.因此,您实现updateUI方法的方式将使其仍然在执行线程中运行。
In your specific case, it seems you wish to notify the UI via your Adapter, so you may do as next:在您的具体情况下,您似乎希望通过您的适配器通知 UI,因此您可以执行以下操作:
public void updateUi(){
Collections.sort(playerArrayList, Collections.reverseOrder(new Comparator<Player>() {
@Override
public int compare(Player p1, Player p2) {
return Integer.valueOf(p1.getScore()).compareTo(p2.getScore());
}
}));
// Notify the UI
final Runnable runnable = () -> adapter.notifyDataSetChanged();
new Handler(Looper.getMainLooper()).post(runnable);
}
where the UI gets notified with the next two lines:在接下来的两行中通知 UI:
final Runnable runnable = () -> adapter.notifyDataSetChanged();
new Handler(Looper.getMainLooper()).post(runnable);
As a side note, if you are only sorting, and the list is quite small which can be completed in a few milliseconds, then probably using a thread isn't a good choice, and you may sort in the UI.作为旁注,如果您只是排序,并且列表很小,可以在几毫秒内完成,那么使用线程可能不是一个好的选择,您可以在 UI 中排序。 Or, if on the contrary, is actually a large list which could block the UI while sorting, then placing such logic in a thread and notify the UI when done is the correct implementation.或者,如果相反,实际上是一个大列表,可能会在排序时阻塞 UI,那么将此类逻辑放在线程中并在完成时通知 UI 是正确的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.