package com.bjsxt.d822.a2; public classSubThread9 extends Thread {/** When multiple objects operate on the same resource at the same time, they must be controlled using a synchronization Mechanism. * 1, when the method to operate a shared resource, the method must be modified by the synchronized Keyword. * 2, When the method is synchronized keyword modification, You also need to wait () and notify () two methods in conjunction with. The wait () method allows the current thread object to enter a wait State. * The Notify () method is for the current thread object to wake the waiting Person. */ Private intsum =0; @Override publicSynchronizedvoidrun () {String name= this. GetName (); System. out. println (name +"statistician, Start Counting ...."); for(inti =1; I <= -; i++) {sum+=i; Try{thread.sleep ( - ); } Catch(interruptedexception E) {e.printstacktrace (); }} System. out. println (name +"statisticians, The cumulative results of 1 to 100 have been statistically completed. "); this. Notify ();//wake up the waiting Person. } //gets the value of sum. //public int getsum () { publicSynchronizedintGetsum () {//error: No write synchronized to modify Getsum () method, so that a java.lang.IllegalMonitorStateException exception occurred Try{System. out. println (thread.currentthread (). getName () +"the manager waits here for the result ..."); this. Wait ();//wait}Catch(interruptedexception E) {}returnsum; }}
package com.bjsxt.d822.a2; public classSubthread9test { public Static voidmain (string[] Args) {System. out. println (thread.currentthread (). getName () +"manager, get to work ..."); SubThread9th=NewSubThread9 (); St.setname ("Zhang San"); St.start (); System. out. println (st.getname () +"statistician, can you give me the results of 1 + 2 + 3 + ... + 100? "); System. out. println ("no problem, But you need to wait a while. "); //try {//Thread.Sleep (15000);//} catch (interruptedexception E) {// //TODO auto-generated Catch block//e.printstacktrace ();// }System. out. println ("the statistical results are:"+St.getsum ()); }}
Because Getsum () is not synchronized decorated in the SubThread9 class, it is written directly to the public int getsum () {} Which led to the appearance of abnormal Java.lang.IllegalMonitorStateException.
Java.lang.IllegalMonitorStateException anomaly caused by improper use of multi-thread synchronous synchronized