有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程Java Swing定时器和线程&For循环中只执行最后一个命令

希望你们都好

我也很抱歉这么冗长。我是Java新手,所以请原谅我缺乏知识/术语/Java惯例

基本上,我已经创建了一个程序,它接受用户输入,并将车辆移动到整个表面区域。所以用户输入可以是“50向左4”,这意味着向前走50米,左转,再向前走4米。 对于车辆,我在JPanel上使用喷漆方法。当车辆向前移动时,它最初会从该区域的一侧跳到另一侧。我想看到它一米一米地移动。因此,我添加了一个摆动计时器,它将车辆移动1米,暂停一秒钟,将车辆移动2米,以此类推

现在的问题是,当我输入命令“50 left 4”时,车辆只需向左转弯,然后向前移动4米。它忽略第一个数字命令。当我输入“34”时也会发生同样的情况,它会忽略3,只向前移动4米。另外,当我进入“左3”时,它会先左转,然后向前移动3米。现在我有了一些方法,可以接收用户的输入,将其切分为一个数组,通过一个循环将数组中的每个元素输入,检查它是否是整数。如果是整数,则向前移动车辆,如果不是,则向左或向右转动车辆。这一切都很好,我很满意

所以我想我应该做的是让这个类可以运行,这样这个方法就可以从一个单独的线程执行,让主线程等待,这样它就不会忽略除了最后一个命令之外的所有命令。但这也不管用

以下是使用摆动计时器一次向前移动车辆1米的移动等级
它实现了Runnable。它是抽象的,因为我需要run方法将用户输入命令作为参数。这就是问题的原因吗

public abstract class Movement implements Runnable {


    static int count = 0;
    static int distance;


    public static void moveRover() {
        // Every 1 second the timer will move the Rover 40 pixels.
        at.translate(0, 40);
    }

    public static void getDistance(int num) {
        distance = num;

    }

    static Timer timer = new Timer(500, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            moveRover();
            count++;
            System.out.println(count);

            if (count == distance) {

                stop();
                System.out.println("Timer stopped");
                count = 0;
            }
        }
    });

    public static void start(int num) {
        getDistance(num);
        System.out.println("Distance rover will travel: " + distance);
        System.out.println("\nTimer started");
        timer.start();
    }

    public static void stop() {
        timer.stop();
    }

    public void run(int num) {
        start(num);
    }

    public Movement(int num) {
        System.out.println("Start RUN method");
        run(num);

    }

下面是另一个运行for循环和线程的类的代码:

public static void action(final String[] commands) {

        for (int i = 0; i < commands.length; i++) {

            if (isInteger(commands[i])) {
                int distance = Integer.parseInt(commands[i]);

                Movement h1 = new Movement(distance) {
                    @Override
                    public void run() {
                        System.out.println("Empty run method");
                    }
                };

                Thread t1 = new Thread(h1);

                t1.start();
                System.out.println(t1.isAlive());

                try {
                    t1.join();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            } else {
                Direction.start(commands[i]);
                String pos = Direction.getDirection(); // GET DIRECTION
            }
        }
    }

我真的很感谢你读到这些,非常感谢

感谢所有回复的人!如果你知道我哪里出了问题,我能做些什么来解决它,你绝对是个救星,我真的很感激:D


共 (0) 个答案