Java,是否将回调的方法视为异步



我用一种方法创建了接口:

public interface ResultCallback {
   void onResult(String message);
}

我有带有以接口作为参数的方法的对象:

public class Command() {
  public void methodWithCallback(int param1, String param2, ResultCallback callback) {
      // There are some calculations
      callback.onResult(param2);
  }
}

然后在我的主Java文件中,我写了这个:

public class Main() { 
   public static void main(String[] args) {
       Command c = new Command();
       c.methodWithCallback(int 0, "SOME STRING", new ResultCallback() {
       @Override
       public void onResult(String str) {
         // work with str
         outsideMethod(str);
       }
      });
   }
   public void outsideMethod(String str) {
      // some code
   }
}

此代码是否可以被视为异步代码?调用outsideMethod来处理参数是否安全?

如前所述,它不是异步的。要使调用异步,该方法应在另一个线程上执行。

你不能调用 outsideMethod,因为它是从静态方法调用的。你需要一个 main 的实例才能调用 outsideMethod。它是否安全取决于代码在做什么。

使其异步的一种方法如下:

public class Command {
    private ExecutorService iExecutor;
    public Command(ExecutorService executor) {
        iExecutor = executor;
    }
    public void methodWithCallback(final int param1, final String param2, final ResultCallback callback) {
        iExecutor.execute(new Runnable() {
            @Override
            public void run() {
                // There are some calculations
                callback.onResult(param2);
            }
        });
    }
}

如果使用线程,您必须知道自己在做什么。事情必须是线程安全的等,这取决于你做事的方式。要在单个线程上运行 Command,请创建一个单线程执行器并将相同的执行器传递给所有 Commmand,如下所示:

ExecutorService executor = Executors.newSingleThreadExecutor();
Command command1 = new Command(executor);
Command command2 = new Command(executor);

最新更新