How to use wait and notify in Java without IllegalMonitorStateException?

后端 未结 12 2098
后悔当初
后悔当初 2020-11-22 02:21

I have 2 matrices and I need to multiply them and then print the results of each cell. As soon as one cell is ready I need to print it, but for example I need to print the [

12条回答
  •  梦如初夏
    2020-11-22 03:17

    Let's say you have 'black box' application with some class named BlackBoxClass that has method doSomething();.

    Further, you have observer or listener named onResponse(String resp) that will be called by BlackBoxClass after unknown time.

    The flow is simple:

    private String mResponse = null; 
     ...
    BlackBoxClass bbc = new BlackBoxClass();
       bbc.doSomething();
    ...
    @override
    public void onResponse(String resp){        
          mResponse = resp;       
    }
    

    Lets say we don't know what is going on with BlackBoxClass and when we should get answer but you don't want to continue your code till you get answer or in other word get onResponse call. Here enters 'Synchronize helper':

    public class SyncronizeObj {
    public void doWait(long l){
        synchronized(this){
            try {
                this.wait(l);
            } catch(InterruptedException e) {
            }
        }
    }
    
    public void doNotify() {
        synchronized(this) {
            this.notify();
        }
    }
    
    public void doWait() {
        synchronized(this){
            try {
                this.wait();
            } catch(InterruptedException e) {
            }
        }
    }
    }
    

    Now we can implement what we want:

    public class Demo {
    
    private String mResponse = null; 
     ...
    SyncronizeObj sync = new SyncronizeObj();
    
    public void impl(){
    
    BlackBoxClass bbc = new BlackBoxClass();
       bbc.doSomething();
    
       if(mResponse == null){
          sync.doWait();
        }
    
    /** at this momoent you sure that you got response from  BlackBoxClass because
      onResponse method released your 'wait'. In other cases if you don't want wait too      
      long (for example wait data from socket) you can use doWait(time) 
    */ 
    ...
    
    }
    
    
    @override
    public void onResponse(String resp){        
          mResponse = resp;
          sync.doNotify();       
       }
    
    }
    

提交回复
热议问题