wait()和notify()导致IllegalMonitorStateException

时间:2016-07-27 11:55:44

标签: java multithreading wait runnable notify

我有两个线程t0和t1,下面分别在代码部分Run_0和Run1中发布了runnables。我想要做的是,当t0写入或执行持续7秒的任务时,t1应该等待。当时 经过7秒后,应通知t1继续工作。我尝试使用wait()和notify()来做到这一点,但在运行时我收到以下发布的错误。

请让我知道如何正确使用wait()和notify()

public static void main(String[] args) {

    t0 = new Thread(new Run_0());
    t1 = new Thread(new Run_1());

    t0.start();
    t1.start();
}

private static class Run_0 implements Runnable {
    public void run() {
        // TODO Auto-generated method stub

        while (true) {
            long startTime = TimeUtils.getTSSec();
            synchronized (this) {
                try {
                    t1.wait(); //<=========Line 27
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            System.out.println("T0 is writing");
            //simulate doing some work
            while( (TimeUtils.getTSSec()-startTime) <= 7) {

            }
            System.out.println("T0 finished writing");
            t1.notify();
            startTime = TimeUtils.getTSSec();

            while( (TimeUtils.getTSSec()-startTime) <= 7) {

            }
        }

    }

}

private static class Run_1 implements Runnable {

    public void run() {
        // TODO Auto-generated method stub

        while(true) {

            System.out.println("T1 is working");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

错误

Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Unknown Source)
at com.example.Main$Run_0.run(Main.java:27)
at java.lang.Thread.run(Unknown Source)

0 个答案:

没有答案