2009-04-21 129 views
1

我有一个叫communicator的类。该类是接收来自另一个程序的事件的线程的侦听器。这个类还有一个方法调用刷新,它发送和执行程序a等待通过侦听器来的响应。如何处理java线程

两种方法都在同一个类中,但是由不同的线程调用。

public void processRefreshEvent(ManagerEvent event){ 
    //processing event 
    //... 
    //I'm done 
    notify(); 
} 


public synchronized void refresh() throws Exception { 
    isRefreshing = true;  
    try { 
        manager.send(new refresh()); 
    } catch (ManagerException e) { 
     isRefreshing = false; 
    } 

    try { 
      wait(5000); 
    } catch (InterruptedException e) { 
    } finally{ 
     isRefreshing = false; 
    } 
} 

执行代码时,上面我得到如下异常:

java.lang.IllegalMonitorStateException: current thread not owner 
     at java.lang.Object.wait(Native Method) 
     at Communicator.refresh(Communicator.java:203) 
     ... 

什么是正确的方法“等”另一个线程来完成。谢谢。

回答

2

您需要在显示器上同步您的线程。例如(使用当前对象作为显示器):

public void processRefreshEvent(ManagerEvent event){ 
     //processing event 
     //... 
     //I'm done 
    synchronized(this) { 
     notify(); // you are basically notifying any thread who has blocked 
        // on this monitor - in our case, the instance of this object 
    } 
} 


public synchronized void refresh() throws Exception { 
     isRefreshing = true;  
     try { 
        manager.send(new refresh()); 
     } catch (ManagerException e) { 
       isRefreshing = false; 
     } 

     try { 
      synchronized(this) { 
       wait(5000); // wait will give up the monitor 
      } 
     } catch (InterruptedException e) { 
     } finally{ 
       isRefreshing = false; 
     } 
} 
+0

要明确,“任何线程”的意思是“任何一个等待线程”,而不是“所有等待线程”。 – erickson 2009-04-21 21:08:19

0

Object.wait()的JavaDoc中: ‘当前线程必须拥有该对象的监视器。’ 所以你需要在你要调用的对象上进行同步。

或者,您可以使用BlockingQueue,它实现了CollectionQueueBlockingQueue做所有的等待和通知的工作。你的线程可以调用take(),这将阻塞,直到数据可用。您可以使用各种插入方法(添加,放入等)将数据添加到队列中。顺便说一句,插入方法调用notify,而take()调用wait

1

方法wait()notify()只能从其实例上当前同步的线程中调用。

宣布“processRefreshEvent”​​,或者更好的是,就在的代码块来修改所使用由refresh方法的状态下,与notify()呼叫在一起。

public void processRefreshEvent(ManagerEvent event){ 
    // processing event 
    synchronized (this) { 
    // modify shared state with results of processing. 
    notify(); 
    } 
} 
0

请仔细阅读java.lang.Object.wait()notify()的Javadoc。

您应该同步的等待()与适当的显示器,在这种情况下:

try{ 
    synchronized(this){ 
      wait(5000); 
    } 
} 
catch (InterruptedException e) { 
} finally{ 
      isRefreshing = false; 
} 
1

你说你要等到另一个线程完成?然后,只需在要等待的Thread对象上调用join()。