本文介绍了wait()和notify()方法,总是IllegalMonitorStateException发生,告诉我当前线程不是所有者为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();
    }
}


推荐答案

需要在对象上保持锁定 wait (您只能在同步块中调用它)

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

此外,在线程上调用 wait 非常不寻常,可能不是你想要的。

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

我不知道你想做什么,但你可能会混淆 wait sleep

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

如果你想等待另一个线程完成, code> anotherThread.join()。

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

这篇关于wait()和notify()方法,总是IllegalMonitorStateException发生,告诉我当前线程不是所有者为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 03:56