Avatar ·

wait()和sleep()在Java中有什么区别?什么时候该用哪个?

大家好!我刚开始学习Java多线程,对两个方法感到困惑:wait()和sleep()。两者似乎都能“暂停”线程,但行为不同,我不明白何时该用哪个。

下面是我写的一个例子。我希望一个线程输出数字,另一个输出字母,交替进行。但结果是一团糟:

public class Test {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(i);
                try { Thread.sleep(1000); } catch (InterruptedException e) {}
            }
        });

        Thread t2 = new Thread(() -> {
            for (char c = 'A'; c < 'F'; c++) {
                System.out.println(c);
                try { Thread.sleep(1000); } catch (InterruptedException e) {}
            }
        });

        t1.start();
        t2.start();
    }
}