你好我试图弄清楚我的主线程每隔1/10或1 / n秒返回一个值的方式,例如......
public class MainGameLoop {
public static void main(String[] args) {
while (!Display.isCloseRequested()) {
//Run Game Logic
//every 1/10th second update skeletal animation
//ever 1/30th second update texture animation
}
}
我一直在试验像这样的单独线程
public class HelloRunnable implements Runnable {
public void run() {
try{
Thread.sleep(500)
System.out.println("Hello from a thread!");
catch(Exectpion e) {
}
}
但是睡眠会影响我主线程的线程。如果我睡了10秒钟,我的主线程会睡眠10秒钟。
我已经尝试了
Runnable z = new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hi");
}
};
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(z);
while (!Display.isCloseRequested()) {
//Run Game logic
}
}
这只在初始化时运行一次,并且延迟" hi"在指定的睡眠量之后,或者这个
Runnable z = new Runnable() {
public void run() {
try {
Thread.sleep(100000);
}catch(Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("hi");
}
};
ExecutorService executor = Executors.newCachedThreadPool();
while (!Display.isCloseRequested()) {
//Run Game logic
executor.submit(z);
}
}
打印出来" hi"和主线程一样快可以刷新。
答案 0 :(得分:2)
public class TimerDemo extends TimerTask
{
public static void main(String[] args)
{
TimerTask tasknew = new TimerDemo();
Timer timer = new Timer();
timer.scheduleAtFixedRate(tasknew, 0, 1000);
}
@Override
public void run()
{
System.out.println("once every 1000 ms");
}
}
所有任务都在同一个线程上运行。在上面的示例中,如果run()
执行时间超过1000毫秒,则下一个计划执行将被延迟。有关详细信息,请参阅javadocs。如果您想要多个线程,请改用ScheduledThreadPoolExecutor。