java - java中for循环内部的后台服务调用?

标签 java for-loop background-service

我希望我能以适当的方式解释问题:) 我有一个对象数组 (handleData)。我从数据库中获取它们。我想通过为每个单独调用服务将它们发送到服务器。 我将服务放在一个 for 循环中以发送所有 handleData(请参阅代码)。

调用服务是在后台完成的。每个人的回应可能不会来,因为他们有条不紊地发送。我必须为我发送的每个 handleData 做一些更新。

问题:当响应到来时,我不确定是否对我想要/正确发送的确切 handleData 执行了所考虑的操作(记录更新)。

private void sendDataOfTemplates() {
    ArrayList<FormHandleData> formHandleDatas = FormHandleData.getDatasFromDB(getContext(), 12, EnumDataStatusOfServer.NoSTATUS.getIntValue(),-1);// true means >> to send / -1 means no limit
    try {
        if (formHandleDatas != null && formHandleDatas.size() != 0) {
            for (int i = 0; i < formHandleDatas.size(); i++) {
                final FormHandleData handleData = formHandleDatas.get(i);
                if (handleData.status_in_server == EnumDataStatusOfServer.OPEN.getIntValue())
                    if (handleData.status_in_app == EnumDataStatusInApp.SAVED.getIntValue() || handleData.status_in_app == EnumDataStatusInApp.EDITED.getIntValue()) {
                        ServiceHelper.getInstance().sendDataOfTemplates(new ServiceHelper.ResponseListener() {
                            @Override
                            public void onResponse(String response) {
                                try {

                                    SimpleResponse simple_response = new Gson().fromJson(response, SimpleResponse.class);
                                    if (simple_response.isSuccessful()) {
                                       handleData.status_in_app = EnumDataStatusInApp.SENT.getIntValue();
                                        FormHandleData.UpdateDataTemplatesInDB(handleData, getContext(),false);
                                    } else {
                                    }
                                } catch (Exception e) {
                                }
                            }

                            @Override
                            public void onErrorResponse(VolleyError error) {
                            }
                        }, handleData);
                    }
            }
        }
    } catch (Exception e) {
    }

}

最佳答案

problem : when the response comes I am not sure that if the regarded action (update of record) is done to the exact handleData that I want/sent properly.

如果我理解正确的话,你是在问你的匿名 ServiceHelper.ResponseListener 子类正在访问的周围局部变量 handleData 是否始终是同一个对象实例,即使尽管在下一个 for 循环中,该变量的值将有所不同。答案是肯定的。所以您不必担心。

如果您想了解更多关于匿名类如何从周围范围捕获变量的信息,请阅读 this part of the Oracle's Java tutorial ,它说:

  • An anonymous class has access to the members of its enclosing class.
  • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

因此,可以访问周围变量的事实意味着从匿名类的角度来看它(有效地)是最终的,即它不会改变。

这里是一个使用多线程的小演示:

package de.scrum_master.app;

public class WhoDoesWhat {
  private String name;
  private final String action;

  public WhoDoesWhat(String name, String action) {
    this.name = name;
    this.action = action;
  }

  public String getName() {
    return name;
  }

  @Override
  public String toString() {
    return name + " -> " + action;
  }
}
package de.scrum_master.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Application {
  private static final Random RANDOM = new Random();

  public static void main(String[] args) {
    List<WhoDoesWhat> peopleDoingSomething = new ArrayList<>();
    peopleDoingSomething.add(new WhoDoesWhat("Galileo", "discover moons of Jupiter"));
    peopleDoingSomething.add(new WhoDoesWhat("Johannes", "determine the laws of planetary motion"));
    peopleDoingSomething.add(new WhoDoesWhat("Albert", "explain the precession of Mercury"));
    peopleDoingSomething.add(new WhoDoesWhat("Edwin", "notice something odd about recession speeds of galaxies"));

    for (WhoDoesWhat personDoingSomething : peopleDoingSomething) {
      new Thread(() -> {
        System.out.println("START " + personDoingSomething);
        try {
          int waitCycles = 1 + RANDOM.nextInt(10);
          for (int cycle = 0; cycle < waitCycles; cycle++) {
            System.out.println("  " + personDoingSomething.getName() + " is still being busy");
            Thread.sleep(250);
          }
        } catch (InterruptedException e) {
        }
        System.out.println("STOP " + personDoingSomething);
      }).start();
    }
  }
}

控制台日志可能如下所示:

START Johannes -> determine the laws of planetary motion
START Albert -> explain the precession of Mercury
START Galileo -> discover moons of Jupiter
START Edwin -> notice something odd about recession speeds of galaxies
  Albert is still being busy
  Johannes is still being busy
  Edwin is still being busy
  Galileo is still being busy
  Galileo is still being busy
  Edwin is still being busy
  Johannes is still being busy
  Albert is still being busy
  Edwin is still being busy
  Galileo is still being busy
  Albert is still being busy
STOP Johannes -> determine the laws of planetary motion
  Edwin is still being busy
  Galileo is still being busy
  Albert is still being busy
  Galileo is still being busy
STOP Edwin -> notice something odd about recession speeds of galaxies
STOP Albert -> explain the precession of Mercury
  Galileo is still being busy
  Galileo is still being busy
  Galileo is still being busy
STOP Galileo -> discover moons of Jupiter

关于java - java中for循环内部的后台服务调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47032499/

相关文章:

java - 文件树比较器

java - 自动添加日志记录事件的 Java Eclipse 插件

Java - 将else语句放入循环中

android - 如何在android中使用服务实现BeaconConsumer

.net - 使用 Microsoft.Extensions.Hosting.WindowsServices 时无法启动 Windows 服务

java - 将工作集配置到 Maven pom.xml 中

java - 尽管设置了属性,Android 工具栏标题、副标题和后退按钮仍不显示

python - 如何让我的计数重置为循环

python - 无法使用 Python for 循环列出文件

应用程序被杀死时Android后台服务正在重新启动