Java中的队列方法?
我正在寻找用Java创建一个模式,我不知道如何正确地完成。。。现在我有其他的解决方案,但我想知道是否有一种方法可以实现这种模式Java中的队列方法?,java,Java,我正在寻找用Java创建一个模式,我不知道如何正确地完成。。。现在我有其他的解决方案,但我想知道是否有一种方法可以实现这种模式 MethodArray methodarray; public QueueSimulation(Method method){ methodarray.add(method); } public RunSimulation(){ methodarray.r
MethodArray methodarray;
public QueueSimulation(Method method){
methodarray.add(method);
}
public RunSimulation(){
methodarray.runall(); // runs all the qued methods in order
}
我有许多不同的方法和不同的名称,我想排队
换句话说,我有一门课
Player.Moveup()
Player.Attack()
Player.FallOnGround()
World.LightsOff()
我有许多不同的方法,但我希望能够将所有这些方法放在一个数组中,并像上面的模式一样运行它们。这看起来像是一个可以使用单线程的方法,它可以创建为匿名类。 通过谷歌搜索,我找到了帮助创建单线程执行器的工厂 以下是一个例子:
public class MethodQueueSimulator {
Collection<Callable<Void>> methodQueue = new LinkedList<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
public static void main(String args[]) throws InterruptedException {
MethodQueueSimulator simulator = new MethodQueueSimulator();
simulator.QueueSimulation(new Callable<Void>() {
@Override
public Void call() throws Exception {
System.out.println("1");
return null;
}
});
// if using java 8+, you can use lambdas instead
simulator.QueueSimulation(() -> {
System.out.println("2");
return null;
});
simulator.QueueSimulation(() -> {
System.out.println("3");
return null;
});
System.out.println("Simulation starts");
simulator.RunSimulation();
System.out.println("Simulation complete");
}
public void QueueSimulation(Callable<Void> method){
methodQueue.add(method);
}
public void RunSimulation() throws InterruptedException {
executor.invokeAll(methodQueue);
// must call shutdown, else process will not exit
executor.shutdown();
}
}
如您所见,事件是按顺序执行的,对invokeAll的调用是阻塞的,这意味着代码执行在继续之前等待任务完成,这就是为什么“Simulation complete”只在最后打印。当然,这个输出并不能证明这个说法,但是你可以自己试试看
您将调用所需的方法,而不是System.out.println。我不知道您的方法具有哪种类型的返回值,所以我选择Void作为可调用项的返回类型。在我看来,这就像单线程执行器一样。另外,请看一下如何将Runnable接口与匿名类或Java8Lambdas一起使用。也许您可以简单地概括一下如何使用单线程执行器来完成我尝试创建的这两个方法。现在看来,我必须为每个方法创建一个单独的类,很遗憾,这不是我想要的,但如果这是实现此模式的最佳方法,那么我必须继续。
Simulation starts
1
2
3
Simulation complete