Thread Communication concept: threads are independent individuals in the operating system, but these individuals cannot become a whole without special processing, and the communication between threads becomes one of the necessary ways for the whole. When a thread has a communication command, the interaction between the system is more powerful, while increasing CPU utilization will enable the developer to effectively grasp and supervise the thread task during processing. Use the Wait/notify method to implement communication between threads. (Note that both methods are the side of the class of object, in other words, Java provides both methods for all objects)
- Wait and notify must be used with the Synchronized keyword
- The Wait method releases the lock, and the Notify method does not release the lock
Example one:
Public classLISTADD1 {Private volatile StaticList List =NewArrayList (); Public voidAdd () {List.add ("BJSXT"); } Public intsize () {returnlist.size (); } Public Static voidMain (string[] args) {FinalListAdd1 List1 =NewListAdd1 (); Thread T1=NewThread (NewRunnable () {@Override Public voidrun () {Try { for(inti = 0; I <10; i++) {list1.add (); System.out.println ("Current thread:" + thread.currentthread (). GetName () + "added an element ..."); Thread.Sleep (500); } } Catch(interruptedexception e) {e.printstacktrace (); } } }, "T1"); Thread T2=NewThread (NewRunnable () {@Override Public voidrun () { while(true){ if(list1.size () = = 5) {System.out.println ("Current thread received notification:" + thread.currentthread (). GetName () + "List size = 5 thread stop ..."); Throw Newruntimeexception (); } } } }, "T2"); T1.start (); T2.start (); }}
View Code
Problem: Thread T2 is a dead loop that has been monitoring the list of size equals 5, which is very bad, T2 has been running, consuming CPU.
So what's the way to improve it?
Example two:
Using Java Communication (wait/notify) to optimize your code
/*** Wait Notfiy method, wait release lock, notfiy not release lock **/ Public classLISTADD2 {Private volatile StaticList List =NewArrayList (); Public voidAdd () {List.add ("BJSXT"); } Public intsize () {returnlist.size (); } Public Static voidMain (string[] args) {FinalLISTADD2 List2 =NewListAdd2 (); //1 instantiation of a lock//when using wait and notify, be sure to work with the Synchronized keyword FinalObject lock =NewObject (); Thread T1=NewThread (NewRunnable () {@Override Public voidrun () {Try { synchronized(lock) { for(inti = 0; I <10; i++) {list2.add (); System.out.println ("Current thread:" + thread.currentthread (). GetName () + "added an element ..."); Thread.Sleep (500); if(list2.size () = = 5) {System.out.println ("Notification has been issued."); Lock.notify (); } } } } Catch(interruptedexception e) {e.printstacktrace (); } } }, "T1"); Thread T2=NewThread (NewRunnable () {@Override Public voidrun () {synchronized(lock) {if(List2.size ()! = 5){ Try{System.out.println ("T2 into ..."); Lock.wait (); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println ("Current thread:" + thread.currentthread (). GetName () + "receive notification thread stop ..."); Throw Newruntimeexception (); } } }, "T2"); T2.start (); T1.start (); } }
View Code
Results: You can see from the following results that the notify does not release the lock until the lock is released after execution
T2 Enter ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Notification has been issued. Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T2 received notification thread stopped. Exception in Thread "T2" Java.lang.RuntimeExceptionat Com.bjsxt.base.conn008.listadd2$2.run (listadd2.java:66) at Java.lang.Thread.run (thread.java:745)
Problems: List size equals 5, T2 is not immediately executed, because T1 has not released the lock, to wait until the T1 execution after the release of the lock, so T2 execution is not timely
Is there any way to optimize the code?
Example three:
Use the Countdownlatch under the Java.util.concurrent package
/*** Wait Notfiy method, wait release lock, notfiy not release lock **/ Public classLISTADD2 {Private volatile StaticList List =NewArrayList (); Public voidAdd () {List.add ("BJSXT"); } Public intsize () {returnlist.size (); } Public Static voidMain (string[] args) {FinalLISTADD2 List2 =NewListAdd2 (); //1 instantiation of a lock//when using wait and notify, be sure to work with the Synchronized keyword//Final Object lock = new Object (); FinalCountdownlatch Countdownlatch =NewCountdownlatch (1); Thread T1=NewThread (NewRunnable () {@Override Public voidrun () {Try { //synchronized (lock) { for(inti = 0; I <10; i++) {list2.add (); System.out.println ("Current thread:" + thread.currentthread (). GetName () + "added an element ..."); Thread.Sleep (500); if(list2.size () = = 5) {System.out.println ("Notification has been issued."); Countdownlatch.countdown (); //lock.notify (); } } //}}Catch(interruptedexception e) {e.printstacktrace (); } } }, "T1"); Thread T2=NewThread (NewRunnable () {@Override Public voidrun () {//synchronized (lock) { if(List2.size ()! = 5){ Try { //System.out.println ("T2 into ..."); //lock.wait ();countdownlatch.await (); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println ("Current thread:" + thread.currentthread (). GetName () + "receive notification thread stop ..."); Throw Newruntimeexception (); //} } }, "T2"); T2.start (); T1.start (); } }
View Code
Result: When the size of list is equal to 5, T2 is executed immediately, and T1 does not affect
Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Notification has been issued. Exception in thread "t2" Current thread: T1 added an element ... Current thread: T2 received notification thread stopped. Java.lang.RuntimeExceptionat Com.bjsxt.base.conn008.listadd2$2.run (listadd2.java:70) at Java.lang.Thread.run ( thread.java:745) Current thread: T1 an element was added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ... Current thread: T1 an element has been added ...
Multithreaded communication (wait/notify)