2016-08-24 87 views
3
方法

我的目标是有包含在继承Thread其run方法弹出一个方法调用从队列中每15秒一次的一类方法调用的队列。这可以通过使用字符串,整数或字符在一个庞大的开关盒中以阴暗的方式完成,但是我想知道是否有其他人对此问题有更为优雅的解决方案。队列中的Java

东西会是这样的?

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(https://docs.oracle .com/javase/tutorial/reflect /) –

+2

看看执行器API – danielbathke

+2

究竟是什么卡住了? – shmosel

回答

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接口有什么问题? – shmosel

+1

'Runnable'会起作用,那是真的。重要的是要处理一些类类型的队列而不是方法 –

+0

提示:你可能想提一下,这可以称为* Command *模式。人们可以围绕这种方法做很多有趣的事情。上帝要小心,不要使用反射。 – GhostCat

0

这一个衬垫(它可在Android API中)给你你想要相同的功能落实:

ScheduledExecutorService s = Executors.newScheduledThreadpool(numThreads);

如果你需要使用反射来运行任意的方法,然后提交到该服务是包装纸各一铜一样容易自定Runnable的说法,并呼吁s.schedule(Runnable,long,TimeUnit);

我想不出一个更优雅,少麻烦的解决方案,以您的问题(使用Java时,至少)。它配备了具有经测试,作为自2004年以来核心Java API的一部分利益 - @CodeBlind