How to use wait and notify in Java without IllegalMonitorStateException?

后端 未结 12 2332
后悔当初
后悔当初 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:00

    I'll right simple example show you the right way to use wait and notify in Java. So I'll create two class named ThreadA & ThreadB. ThreadA will call ThreadB.

    public class ThreadA {
        public static void main(String[] args){
            ThreadB b = new ThreadB();//<----Create Instance for seconde class
            b.start();//<--------------------Launch thread
    
            synchronized(b){
                try{
                    System.out.println("Waiting for b to complete...");
                    b.wait();//<-------------WAIT until the finish thread for class B finish
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
    
                System.out.println("Total is: " + b.total);
            }
        }
    } 
    

    and for Class ThreadB:

    class ThreadB extends Thread{
        int total;
        @Override
        public void run(){
            synchronized(this){
                for(int i=0; i<100 ; i++){
                    total += i;
                }
                notify();//<----------------Notify the class wich wait until my    finish 
    //and tell that I'm finish
                }
            }
        }
    

提交回复
热议问题