Java中的方法队列

3
我的目标是创建一个继承自Thread类的包含方法调用队列的对象,其run()方法每隔15秒弹出一个方法调用。虽然可以使用字符串、整数或字符在一个巨大的switch case语句中完成此操作,但我想知道是否有更优雅的解决方案。
是否有类似以下的解决方案?
public class Potato extends Thread{
    Queue<Methods> methodsQueue = new LinkedList<Methods>();

    public Potato(){}
    run(){
        methodsQueue.poll();//This would execute a method
    }

    //Methods of this class...
}

1
我认为你会想要研究一下反射API - Dennis Soemers
2
请查看执行器API。 - danielbathke
2
你卡在哪里了? - shmosel
1
简单的解决方案是使用 java.util.Timer,每 15 秒执行一次,并从某个单函数接口类型的队列中获取任务,你可以通过编写 Lambda 表达式轻松地填充通用操作。 - NESPowerGlove
2
这个一行代码(在Android API中可用)提供了您正在尝试实现的相同功能:ScheduledExecutorService s = Executors.newScheduledThreadpool(numThreads); 如果您需要使用反射运行任意方法,则将它们提交到此服务就像将每个方法包装在自定义Runnable参数中并调用s.schedule(Runnable,long,TimeUnit)一样容易。我无法想象有比这更优雅、更简便的解决方案来解决您的问题(至少在使用Java时是如此)。而且,它作为核心Java API的一部分已经被测试和使用自2004年以来。 - CodeBlind
显示剩余5条评论
2个回答

3
您可以使用接口封装您想要调用的方法:
public interface MethodWrapper {
  void execute();
}

public class Potato extends Thread{
  Queue<MethodWrapper> methodsQueue = new LinkedList<>();
  public Potato(){}
  run(){
   methodsQueue.poll().execute();
  }

//Methods of this class...
}

1
Runnable 可以工作,这是真的。重要的是处理某个类类型的队列,而不是方法。 - Nir Levy
提示:你可能想提到这可以被称为命令模式。使用这种方法可以做很多有趣的事情。但是请注意,不要使用反射。 - GhostCat

0

这个一行代码(在Android API中可用)提供了您正在尝试实现的相同功能:

ScheduledExecutorService s = Executors.newScheduledThreadpool(numThreads);

如果您需要使用反射运行任意方法,则将它们提交到此服务与包装每个方法的自定义Runnable参数一样容易,并调用s.schedule(Runnable,long,TimeUnit);

我无法想象有比这更优雅、更简便的解决方案来解决您的问题(至少在使用Java时是如此)。而且,它作为核心Java API的一部分已经被测试和使用自2004年以来。- @CodeBlind


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接