推荐一个更好的办法把同步方法,在Java中对异步 [英] Recommend a better way to turn synchronous methods to asynchronous in Java

查看:614
本文介绍了推荐一个更好的办法把同步方法,在Java中对异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一类是被同步运行的一些方法。我想他们异步运行,第一个想法是把它包起来,并用开关枚举来决定哪个函数被调用。但对于每一个调用的方法,我需要在包装类的新方法和新的枚举。它看起来是这样的:

In a classes are some methods that are run synchronously. I would like them to run asynchronously, the first idea was to wrap it, and use switch enum to decide which function should be called. But for every method called, I needed a new method in the wrapper class and a new enum. It looks like this:

public class QueuedShow implements InterfaceShowAlert, Runnable {
    private Class Action {
       String param1;
       public static enum ActionEnum{
          NEW, CHECK, UPDATE, DELETE, DISPLAY;
       }
       public ActionEnum todo;
       public Action(ActionEnum todo, Object param){
          this.todo=todo;
          this.param1=param;
       }
    }
    private BlockingQueue<Action> actionList;
    public void run(){
       while(true){
           Action action=actionList.take(); //THIS waits until queue isn't empty
           switch(action.todo){
           case NEW: //Call original function
              ....
           }
       }
    }
    public void new(String param){
       actionList.add(new Action(NEW, param));
    }
}

然后我学到了反思和我有一个新的想法。这是调用使用字符串,而不是直接的方法调用的方法。
该包装类读取并解析字符串,并获取使用反射类和含方法。它把参数和方法的对象变成一个类,它被放入队列中。现在,类使用Method.invoke(PARAMS),而不是使用枚举切换。但这样做的问题是,编译时间类型检查丢失

Then I learned about reflection and I got a new idea. That is to invoke methods using strings instead of direct method calls. The wrapper class reads and parses the strings, and gets the class and containing method using reflection. It puts the parameters and Method object into a class, which is put into a queue. Now the class uses Method.invoke(params) instead of using a enum to switch. But the problem of this is that compiler time type checking is lost.

当然,这一切工作只能是void的方法,当然我们可以用未来的类太返回值。

Of course, all this works for only methods that are void, but of course we could use the Future class to return values too.

现在有一个已经实施了转向那些异步同步调用,或者你知道,这是否任何其他方法的任何框架。

Now is there any framework that already has implemented turning synchronous calls to asynchronous ones, or do you know of any other method that does this.

推荐答案

这是做它的推荐方式:

abstract public class Action<T> implements Runnable {
  private final T param;

  public Action(T param) {
    this.param = param;
  }

  @Override
  public final void run() {
    work(param);
  }

  abstract protected void work(T param);
}

ExecutorService exec = Executors.newSingleThreadExecutor();
while (/* more actions need to be done */) {
  exec.submit(action);
}
exec.shutdown();
exec.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

这篇关于推荐一个更好的办法把同步方法,在Java中对异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆