我想安排一次一次的任务,原因和情况是什么:
在这种情况下,我有一个多个事件的游戏,例如一个纸牌游戏,有3场比赛,每一场‘比赛’有用户赢得2的3个游戏,以赢得比赛。
3局中最好3局3胜3局3胜3局
现在我想每3分钟开始一场比赛,每场比赛都需要1分钟,例如
小时游戏
当然,每个任务只需要开始一次,以后就再也不会发生了(它将再次发生,但不是在相同的玩家/游戏ID/匹配ID)。
因此,我认为我应该做的是创建一个匹配任务与一个可运行,该运行将创建一个任务为每个游戏。在游戏任务完成后,我应该关闭这个线程,或者有其他的东西可以启动类似于上面的情况?
我已经读过很多关于Timer en ScheduledExecutorService类的文章,但是其中哪一个是最好的,还有另一个更好的例子吗?
耽误您时间,实在对不起!
编辑:
当然,总是在你提出问题之后,你会发现一些事情。所以我会在这里发布我的课程,这不是动态类,而是一个测试类。当我想要它的时候,我唯一的问题是,当运行程序被执行并完成时,他将被从线程中移除。或者,在这些事件发生100.000.000之后,线程拉会满吗?
import java.util.Timer;
import java.util.TimerTask;
import com.ibm.icu.util.GregorianCalendar;
public class TaskScheduler {
public static GregorianCalendar result = new GregorianCalendar(2014, 2, 5, 15, 54, 0);
public static GregorianCalendar resulta = new GregorianCalendar(2014, 2, 5, 15, 55, 00);
public static void main(String[] args) throws InterruptedException {
System.out.println("First thing: " + result.getTime());
System.out.println("second thing: " + resulta.getTime());
createNewTimerTask(1);
createNewTimerTask(21);
createNewTimerTask(31);
createNewTimerTask(41);
createNewTimerTask(51);
createNewTimerTask(61);
createNewTimerTask(71);
createNewTimerTask(81);
createNewTimerTask(91);
createNewTimerTask(01);
createNewTimerTask(111);
createNewTimerTask(122);
createNewTimerTask(133);
createNewTimerTask(144);
createNewTimerTask(155);
createNewTimerTask(166);
createNewTimerTask(177);
}
private static void createNewTimerTask(int id) {
Timer myTimer = new Timer();
myTimer.schedule(new Test(id), resulta.getTime());
}
}
class Test extends TimerTask {
public static GregorianCalendar result = new GregorianCalendar(2014, 2, 5, 15, 52, 0);
private int id;
Test(int id) {
this.id = id;
}
@Override
public void run() {
try {
Thread.sleep(5000l);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ID: " + id);
}
}发布于 2014-03-05 15:10:06
计时器任务结束后,它将被垃圾收集。在100000个事件之后,创建另一个计时器任务将正常运行。
https://stackoverflow.com/questions/22200440
复制相似问题