根据您的流程的具体情况,您可能不需要进行线程处理(相信我,这是您宁愿避免的事情,无论大孩子们做得多么酷和有趣)。
解决该问题的一种方法是设置事件队列。
在伪代码中
enum EVENTTYPES = {PEEL=0, WORK=1};
struct Event = {
int eventType;
int* data;
}
filoQueue eventQueue;
array sQuidPlayers = [new Squid(), new Squid(), new Squid()];
void eventLoop () {
int player;
for each player in sQuidPlayers {
eventQueue.push(new Event(EVENTTYPES.WORK, player.id));
}
for each event in eventQueue {
game.doEvent(event)
}
}
所以在这里你每秒运行事件循环 25 次、30 次或 60 次,无论你想以何种帧速率运行。你为此使用了一个计时器(我确定在某个地方的 java 中有一个)
然后 doEvent 将尝试在对应的播放器实例上查找一些对应的方法。Squid 类的 work 方法会做一些很小的工作,然后停止,在循环中等待下一次。阵列中的每个 Squid 都轮到他们做自己的一小部分工作。反过来,工作方法可以将 PEEL 事件放入事件队列中。此时,下一次循环时,可能会调用一些相应的剥离方法。也许在某个中心游戏类上,带有发起剥离事件的玩家的 id。您将如何分派这些事件的逻辑放入那里的 doEvent 方法中。doEvent 反过来可以将一个对象传递给每个事件接收者,以便接收者可以将自己的事件对象放入队列中,以便下次在循环中运行。(或者,“对于每个事件”
The trick is figuring out how to break your long running work into a tiny parcel of work, figure out how to save the results of that work, and pick it up later where you left off the next time the work method is called. If all the players are well behaved, they can all share a thread without getting stuck.
If you're going to go down the threaded path, the issues about who can access what bit of memory and when get a little bit more complicated.