首页 > 解决方案 > 使用独立的 wait() 方法和使用类的任何实例( obj.wait() )有什么区别

问题描述

我正在尝试以交错方式执行 2 个线程。一个是打印奇数,另一个是打印偶数到控制台(<=100)。我希望输出为:1 2 3 4 5 6 7 8 9 10 .... 等等。即他们应该按顺序一个接一个地执行。

这是此的代码:

class Monitor{
    boolean flag = false;
}

class OddNumberPrinter implements Runnable{
    Monitor monitor;
    OddNumberPrinter(Monitor monitor){
        this.monitor = monitor;
    }

    @Override
    public void run() {
        for (int i = 1; i<100; i+=2){

            synchronized (monitor){
                while(monitor.flag == true){
                    try {
                        wait();
                    } catch (Exception e) {}
                }
                System.out.print(i+"  ");
                monitor.flag = true;
                notify();
            }
        }
    }
}
class EvenNumberPrinter implements Runnable{
    Monitor monitor;
    EvenNumberPrinter(Monitor monitor){
        this.monitor = monitor;
    }

    @Override
    public void run() {
        for (int i = 2; i<101; i+=2){
            synchronized (monitor){
                while (monitor.flag == false){
                    try {
                        wait();
                    } catch (Exception e) {}
                }
                System.out.print(i + "  ");
                monitor.flag = false;
                notify();
            }
        }
    }
}
public class InterleavingThreads {

    public static void main(String[] args) throws InterruptedException {
        Monitor monitor = new Monitor();
        Thread t1 = new Thread(new OddNumberPrinter(monitor));
        Thread t2 = new Thread(new EvenNumberPrinter(monitor));

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

当我独立使用wait() 和 notify()时,它会引发异常,但使用 monitor.wait() 和 monitor.notify()会给出正确的输出。请解释这两者的区别。

标签: javamultithreadingwaitnotify

解决方案


推荐阅读