2016-08-24 93 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