我正在尝试执行一项任务并等待它完成,一切正常,但是当我尝试在 for
循环内执行相同操作时,FutureTask
仅执行一次:
for(int i = 0; i < days.length; i++){
/*
actions to get an array called arr,
but in this code I will just put 20 on this second for loop
*/
for(int i2 = 0; i2 < 20; i2++){
Runnable action = new Runnable() {
@Override
public void run() {
//when I add this line which is add a view to a relative layout, it executes only once
RelativeLayout main_layout = v.findViewById(R.id.main);
main_layout.addView(a_view);
/////////////////////////////////////////////////////////////////////////
Log.i("Message" , "Executed");
}
};
RunnableFuture<Void> task = new FutureTask<>(action , null);
v.post(task);
task.get();
}
}
该任务只执行一次,应该重复 20 次,那么可能是什么问题?
最佳答案
经过大量测试,我终于解决了这个问题,我唯一要做的就是删除最后一行 task.get()
所以代码将是这样的:
for(int i = 0; i < days.length; i++){
/*
actions to get an array called arr,
but in this code i will just put 20 on this second for loop
*/
for(int i2 = 0; i2 < 20; i2++){
Runnable action = new Runnable() {
@Override
public void run() {
layout, it excute only once
RelativeLayout main_layout = v.findViewById(R.id.main);
main_layout.addView(a_view);
Log.i("Message" , "Executed");
}
};
RunnableFuture<Void> task = new FutureTask<>(action , null);
v.post(task);
//task.get(); removed
}
}
关于java - Android Studio FutureTask 在 for 循环中只执行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62313774/