简体   繁体   English

让一部分Java程序等待…而不是整个程序

[英]Make a part of a java program wait… not the whole program

I have a flower game that is supposed to drop flowers at predetermined times. 我有一个花游戏,应该在预定的时间放花。 I have a level class and level1() is a method. 我有一个级别类,而level1()是一个方法。 Inside the level1 method i use... 在我使用的level1方法内部...

Thread.wait(10000);

but it makes the whole program wait until it hits that mark. 但它会使整个程序等到达到该标记为止。 I want the program to load up then do the wait. 我要加载程序,然后等待。 I also tried... 我也尝试过...

public static void waiting(int n) {        
    long t0, t1;

    t0 = System.currentTimeMillis();

    do{
        t1 = System.currentTimeMillis();
    }
    while (t1 - t0 < n);
}

But it does not make any difference either. 但这也没有任何区别。 Is there a better way to do this? 有一个更好的方法吗? Here is the methods code... 这是方法代码...

    package net.blockydigital;

    public class Level {
        RedFlower rf;
        PinkFlower pf;
        WhiteFlower wf;
        YellowFlower yf;
        public Level(){
            rf = new RedFlower();
            pf = new PinkFlower();
            wf = new WhiteFlower();
            yf = new YellowFlower();
        }
        public void level1(){
            try{
            Thread.sleep(10000);
            }catch(Exception e){
                e.printStackTrace();
            }
            rf.dropFlower();
        }
     }    

And then this is where i call the code... 然后这就是我调用代码的地方...

    public PlayGame(){
    sc = new ShoppingCart();
    pf = new PinkFlower();
    rf = new RedFlower();
    wf = new WhiteFlower();
    yf = new YellowFlower();
    s = new Shoes();
    l = new Level();
    addKeyListener(new AL());
    setFocusable(true);
    setBackground(Color.WHITE);
    clock = new Timer(5, this);
    clock.start();
    l.level1();
}

I hope adding this code helps!!! 我希望添加此代码有帮助!!!

I have no Java experience, but you should simply call the level1 method in another thread than the main thread. 我没有Java经验,但是您应该只在不同于主线程的另一个线程中调用level1方法。 This way the program runs and the thread.sleep is only there for the level1 method. 这样,程序运行,并且thread.sleep仅适用于level1方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM