等待执行功能而不冻结过程

时间:2019-10-24 13:55:57

标签: java time

我想在2行运行后等待300ms,以再次运行相同的2行,而不冻结线程。

wait(300);Thread.sleep(300);,以及我在SO上发现的一些循环(如下),要么冻结线程,干净退出(?),要么通过运行函数一百万次使线程滞后。 >

我想等待300毫秒然后运行

mc.player.rotationPitch = 90;
mc.playerController.processRightClick(mc.player, mc.world, hand);

不冻结线程,因为有时如果线程被冻结,它的运行时间不正确,如果用户每次都要冻结,这会给用户带来烦恼。

我尝试过wait, Thread.sleepTimeUnit.MILLISECONDS.sleep

                long lastNanoTime = System.nanoTime();
                long nowTime = System.nanoTime();
                while(nowTime/1000000 - lastNanoTime /1000000 < 300 )
                {
                    nowTime = System.nanoTime();
                    System.out.println("KAMI: Tried to pick up bucket");

                } 

我已经显示了上面的相关示例。 Full code is here

预期:线程正常工作,我的2行(旋转螺距和右键单击)在上一个旋转螺距和右键单击之后运行300毫秒

实际结果:在代码中注释。根据使用的线程的方法,滞后,退出或崩溃

1 个答案:

答案 0 :(得分:0)

您将需要另一个线程来“不冻结”当前线程。可以很容易地做到这一点,就像:

import java.lang.Thread;

public class Main {

    public static abstract class After extends Thread {

        private int sleep = 0;

        public After(int sleep) {
            this.sleep = sleep;
        }

        public void run() {
            try {
                Thread.sleep(this.sleep);
            } catch(InterruptedException e) {
                //do something with e
            }
            this.after();
        }

        public abstract void after();
    }

    public static void main(String[] args) {
        After after = new After(300) {
            public void after() {
                //mc.player.rotationPitch = 90;
                //mc.playerController.processRightClick(mc.player, mc.world, hand);
                System.out.println("testing");
            }
        };
        after.start(); //this will execute the code in 300 ms

        //do what ever you want to do during the 300ms

        after.join(); //join all threads at the end of your code
        System.out.println("done");
    }
}

要创建延迟时,请使用After。希望这会有所帮助!