1

运行此程序时,我得到了IllegalMonitorStateException因为 Even 线程试图在它没有锁定对象时发出通知isEven。为什么会这样?如果线程锁定了对象,则它应该只能进入同步块内部。

public class NumPrinter implements Runnable{

    public static Boolean isEven = true;
    private boolean isEvenThread;
    private int i;

    public void run() {
    while(i < 100){
     synchronized(isEven){
            boolean notPrinting = (isEven ^ isEvenThread);
            System.out.println(notPrinting);
            if(notPrinting) {
                try {
                    isEven.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }       
            System.out.print(i + ",");
            i = i+2;
            isEven = !isEven;
            isEven.notifyAll();
        }
     }
    }

    public NumPrinter(boolean isEvenThread) {

        this.isEvenThread = isEvenThread;   
        if(isEvenThread)
            i = 0;
        else 
            i = 1;
    }
}

public class MultiThreading {

    public static void main(String[] args) {

        Thread oddt = new Thread(new NumPrinter(false), "Odd");
        Thread event = new Thread(new NumPrinter(true), "Even");

        event.start();
        oddt.start();


    }
}
4

2 回答 2

2

您可能需要在常量对象上同步/等待/通知。也将 声明isEven为 volatile。最后,按照官方文档的建议wait(),将call 放入循环中检查循环条件:

public class NumPrinter implements Runnable {
    private static final Object monitor = new Object();
    private static volatile boolean isEven = true;
    private final boolean isEvenThread;
    private int i;

    @Override
    public void run() {
        while (i < 100) {
            synchronized (monitor) {
                while (isEven ^ isEvenThread) {
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(i + ",");
                i = i + 2;
                isEven = !isEven;
                monitor.notifyAll();
            }
        }
    }
    ...
}
于 2015-11-12T12:40:32.397 回答
1

我不是 Java 专家,但您在此处重写同步令牌:

isEven = !isEven;

这可能不是您遇到的唯一问题,但至少使用另一个同步令牌(不会被重写)。

于 2015-11-12T12:26:51.230 回答