How to use wait and notify in Java without IllegalMonitorStateException?

后端 未结 12 2089
后悔当初
后悔当初 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
                }
            }
        }
    
    0 讨论(0)
  • 2020-11-22 03:02

    For this particular problem, why not store up your various results in variables and then when the last of your thread is processed you can print in whatever format you want. This is especially useful if you are gonna be using your work history in other projects.

    0 讨论(0)
  • 2020-11-22 03:03

    This looks like a situation for producer-consumer pattern. If you’re using java 5 or up, you may consider using blocking queue(java.util.concurrent.BlockingQueue) and leave the thread coordination work to the underlying framework/api implementation. See the example from java 5: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html or java 7 (same example): http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingQueue.html

    0 讨论(0)
  • 2020-11-22 03:07

    notify() needs to be synchronized as well

    0 讨论(0)
  • 2020-11-22 03:08

    Do you need to thread this at all ? I'm wondering how big your matrices are, and whether there's any benefit in having one thread print whilst the other does the multiplication.

    Perhaps it would be worth measuring this time before doing the relatively complex threading work ?

    If you do need to thread it, I would create 'n' threads to perform the multiplication of the cells (perhaps 'n' is the number of cores available to you), and then use the ExecutorService and Future mechanism to dispatch multiple multiplications simultaneously.

    That way you can optimise the work based on the number of cores, and you're using the higher level Java threading tools (which should make life easier). Write the results back into a receiving matrix, and then simply print this once all your Future tasks have completed.

    0 讨论(0)
  • 2020-11-22 03:10

    You have properly guarded your code block when you call wait() method by using synchronized(this).

    But you have not taken same precaution when you call notify() method without using guarded block : synchronized(this) or synchronized(someObject)

    If you refer to oracle documentation page on Object class, which contains wait() ,notify(), notifyAll() methods, you can see below precaution in all these three methods

    This method should only be called by a thread that is the owner of this object's monitor

    Many things have been changed in last 7 years and let's have look into other alternatives to synchronized in below SE questions:

    Why use a ReentrantLock if one can use synchronized(this)?

    Synchronization vs Lock

    Avoid synchronized(this) in Java?

    0 讨论(0)
提交回复
热议问题