wait() and notify() method , always IllegalMonitorStateException is happen and tell me current Thread is not Owner Why?

好久不见. 提交于 2020-01-16 16:08:23

问题


package pkg_1;

public class ExpOnWaitMethod extends Thread {

    static Double x = new Double(20);


    public static void main(String[] args) {

        ExpOnWaitMethod T1 = new ExpOnWaitMethod();
        ExpOnWaitMethod T2 = new ExpOnWaitMethod();

        T1.start();

        T2.start();

    }

    public void run() {

        Mag mag = new Mag();

        synchronized (x) {

            try {
                for (int i = 1; i < 10; i++) {
                    mag.nop(Thread.currentThread());
                    x = i * 2.0;

                }

            } catch (InterruptedException e) {

                e.printStackTrace();
            }

        }
    }

}

class Mag {
    char ccc = 'A';

    public void nop(Thread thr) throws InterruptedException {

        System.out.print(ccc + " ");
        ccc++;

        if (thr.getState().toString().equalsIgnoreCase("runnable"))
            Thread.currentThread().wait();
        //thr.notify();
    }
}

回答1:


You need to hold the lock on the object you want to wait on (you can only call it within a synchronized block).

Also, calling wait on a Thread is very unusual and probably not what you want.

I am not sure what you are trying to do, but could you be confusing wait with sleep?

If you want to wait for another thread to finish, that would be anotherThread.join().




回答2:


Before you call wait on an object, you must acquire that object's lock:

syncrhonized(obj)
{
    obj.wait();
}

Your code is calling wait on a Thread object without acquiring the lock first.

I assume this is just a simplified test case to show your problem, but note that you probably want to be calling wait on an object that is accessible from all threads, not on the Thread objects themselves.




回答3:


Someone should cite the API contract for java.lang.Object.wait(), which explains this directly. If a method raises an exception, read the documentation.

When in doubt, read the contract. (Bill McNeal on NewsRadio always kept his in his jacket pocket, a good metaphor for the JavaDoc API.. see "Crazy Prepared" under NewsRadio and ponder the imponderable.)



来源:https://stackoverflow.com/questions/3903039/wait-and-notify-method-always-illegalmonitorstateexception-is-happen-and-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!