java线程,我的代码有什么问题

时间:2012-03-28 14:50:58

标签: java multithreading

我想在另一个线程中更新一个Object,然后在当前线程中访问它:

 public Object getValueAt(final int rowIndex, int columnIndex) {
            data.getRealm().exec(new Runnable(){
                @Override
                public  void run() {

                    System.out.println("Object at " + rowIndex  + " in WritableList is "  + data.get(rowIndex));
                    object = (DOModel) data.get(rowIndex);
                    System.out.println(object);
                    object.notify();
                }
            });
// suspend current thread
            try {
                synchronized (object){
                    object.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(columnIndex == 0){
                System.out.println(object);
                return object.getId();
            }
    }

但是当我运行我的代码时,会发生java.lang.IllegalMonitorStateException。

我更改了代码,看到代码中的注释: 修改--------------------------------

    public Object getValueAt(final int rowIndex, int columnIndex) {
            data.getRealm().exec(new Runnable(){
                @Override
                public  void run() {
                    System.out.println("Object at " + rowIndex  + " in WritableList is "  + data.get(rowIndex));
                    object = (DOModel) data.get(rowIndex);
                    synchronized(object){
                        object.notify();
                    }
                }
            });
            try {
                synchronized (object){
                    object.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
// this line below is never executed.
                System.out.println(object);
            if(columnIndex == 0){

                return object.getId();
            }
    }

2 个答案:

答案 0 :(得分:4)

为了能够通知,您需要在监视器上进行同步。你需要做:

synchronized (object) {
   object.notify();
}

而不是run()中的非同步notify()。

你将以任何方式遇到竞争条件。如果尚未在单独的线程中检索到它,则主线程可能会尝试在object上进行同步。

最好是定义一个单独的锁/监视器,并将其用于同步和通知。

第二次编辑: 另外:如果单独的线程检索对象并在主线程等待之前通知它,它可能无限期地等待。

答案 1 :(得分:1)

notify()调用应位于同一监视器的同步块中