Java 对象的wait和notify方法


public class Main {

    private static int sec = 5;

    public static void main(String[] args) {

        Teacher teacher = new Teacher();

        new Thread(() ->  {
            synchronized (teacher) {
                System.out.println("老师等待铃响...");
                try {
                    teacher.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                teacher.teach();
                System.out.println("学生: 老师好");
            }
        }).start();

        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (teacher) {
                    if (--sec == 0) {
                        System.out.println("上课了 通知老师上课");
                        teacher.notify();
                        break;
                    } else {
                        System.out.println("还有" + sec + "秒上课");
                    }
                }
            }
        }).start();

    }

    static class Teacher {
        public void teach() {
            System.out.println("老师: 上课!");
        }
    }
}

你可能感兴趣的:(Java 对象的wait和notify方法)