java同步方法,推荐一个更好的办法把同步方法,在Java中对异步

本文探讨了如何将同步方法转换为异步执行。作者首先尝试使用枚举和包装类实现,然后转向反射机制来根据字符串调用方法。虽然反射提供了更大的灵活性,但失去了编译时类型检查。最后,提出了一个推荐的方法,即使用抽象类和Runnable接口,通过ExecutorService实现异步任务提交。这种方法简化了代码并保持了类型安全性。
摘要由CSDN通过智能技术生成

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 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));

}

}

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.

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.

解决方案

This is the recommended way of doing it:

abstract public class Action 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);

}

with:

ExecutorService exec = Executors.newSingleThreadExecutor();

while (/* more actions need to be done */) {

exec.submit(action);

}

exec.shutdown();

exec.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值