Java 如何使用Thread.sleep()避免while()

Java 如何使用Thread.sleep()避免while(),java,arrays,multithreading,while-loop,Java,Arrays,Multithreading,While Loop,我从大学得到了一个练习,将一个班级机器人编程为线程,它从装配线(基本上是一个数组)中拾取一些东西,等待给定的时间,然后将其放在另一条装配线上。您必须重复该操作,直到机器人从阵列中拾取特定元素。装配线阵列包含打印板元素 以下是我的解决方案: public class Robot extends Thread { private final AssemblyLine lineIn; private final AssemblyLine lineOut; private fi

我从大学得到了一个练习,将一个班级机器人编程为线程,它从装配线(基本上是一个数组)中拾取一些东西,等待给定的时间,然后将其放在另一条装配线上。您必须重复该操作,直到机器人从阵列中拾取特定元素。装配线阵列包含打印板元素

以下是我的解决方案:

public class Robot extends Thread {

    private final AssemblyLine lineIn;
    private final AssemblyLine lineOut;
    private final long time;

    public Robot(AssemblyLine lineIn, AssemblyLine lineOut, long time) {
        this.lineIn = lineIn;
        this.lineOut = lineOut;
        this.time = time;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        try {
            PrintedBoard printedBoard = null;
            while (printedBoard != PrintedBoard.STOPPER) {
                printedBoard = lineIn.pickUp();
                sleep(time);
                lineOut.putDown(printedBoard);
            }
        } catch (InterruptedException ie) {}
    }
}
正如我所说,机器人线程有一个装配线lineIn,其中包含打印板,而lineOut在开始时不包含任何内容。任务是从列队中挑选一块印制板,等待给定的时间,然后将其放在列队中。 您必须重复此操作,直到拿起印制板挡块

我试着做了一个while循环。问题是我们必须使用Thread.sleep,我听说这与while循环相结合会产生巨大的开销。
你知道除了while,我还可以使用其他选项吗?

一个没有睡眠的while循环,也称为忙等待,它会在等待过程中一直消耗cpu时间,因此会产生你所说的“开销”


Thread.sleep()正好可以避免这种情况。当线程休眠时,它不会占用任何cpu时间。因此,您的解决方案非常好。

“问题是我们必须使用Thread.sleep,我听说这与while循环相结合会产生巨大的开销。”
--您有相关文档或链接吗?您所说的开销是什么意思?您是否尝试过使用消费者-生产者模式?我在浏览器历史记录中找不到它。我认为这是对一些人问题的回答,有人说,与睡眠相结合会产生巨大的开销@我想你可能记错了什么。今后,请避免使用“我听到了…”类型的语句,而是使用链接备份此类语句。