如何使用Thread.sleep()

时间:2017-12-10 14:13:38

标签: java arrays multithreading while-loop

我从大学开始练习编程一个类机器人作为线程从AssemblyLine(基本上是一个数组)中拾取一些东西,等待一段时间,然后将其放在另一个AssemblyLine上。您必须重复此操作,直到机器人从阵列中拾取特定元素。 AssemblyLine数组包含PrintedBoard元素。

这是我的解决方案:

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) {}
    }
}

就像我说的那样,机器人线程有一个AssemblyLine lineIn,其中包含PrintedBoards和lineOut,它在开头不包含任何内容。任务是从lineIn中选择一个PrintedBoard,等待给定的时间,然后将其放在lineOut上。 您必须重复此操作,直到您拿起PrintedBoard STOPPER。

我试着用while循环来做。问题是我们必须使用Thread.sleep,并且我听说这会产生与while循环相结合的大量开销。 你知道我可以使用的任何其他选项吗?

1 个答案:

答案 0 :(得分:1)

没有睡眠的while循环,也称为忙等待会在等待时一直消耗cpu时间,因此在调用它时会产生“开销”。

Thread.sleep()就是为了避免这种情况。当线程休眠时,它不消耗任何CPU时间。所以你的解决方案非常好。