Public classShareresourse {PrivateString name; PrivateString Gender; Private Booleanisempty=true;//indicates that the data is empty /*** Producer stores data in shared resources * Name storage names * Gender stored gender*/ synchronized Public voidpush (String name,string gender) {Try { while(!isempty) {//current is false, storage is not empty, waiting for consumer consumption,//called using a synchronous lock object, which means that the current thread releases the synchronization lock and can only be awakened by other threads This. Wait (); } //~~~~~~ began to consume ~~~~~~~ This. Name =name; Thread.Sleep (10); This. gender=gender; //~~~~~~ began to consume ~~~~~~~~isempty=false;//not empty needs a consumer spending This. Notify ();//Wake up a consumer}Catch(Exception e) {e.printstacktrace (); } } /*** Consumers remove data from shared resources*/ synchronized Public voidpopup () {Try { while(IsEmpty) {//current is true, storage is empty, waiting for producer to produce,//called using a synchronous lock object, which means that the current thread releases the synchronization lock and can only be awakened by other threads This. Wait (); } //~~~~~~~~ started production of ~~~~~~~~~~~~~Thread.Sleep (10); System.out.println ( This. Name + "--" + This. Gender); //~~~~~~~~ end of production ~~~~~~~IsEmpty =true;//is empty and needs to be produced This. Notify ();//Wake up a producer}Catch(Exception e) {e.printstacktrace (); } }}
Producers
//producers Public classProductImplementsRunnable {//Shared resource Objects PrivateShareresourse Resourse =NULL; PublicProduct (Shareresourse resourse) { This. Resourse =Resourse; } Public voidrun () { for(inti = 0; I < 500; i++) { if(i%2==0) Resourse.push ("Brother Chun ~", "male"); ElseResourse.push ("Sister Feng", "female"); } }}
Consumers
Packagethread communication; Public classConsumerImplementsRunnable {PrivateShareresourse resourse=NULL; PublicConsumer (Shareresourse resourse) {//using the constructor to pass Resourse This. resourse=Resourse; } @Override Public voidrun () { for(inti = 0; I < 500; i++) {resourse.popup (); } }}
Test class
package thread communication; public class App { public static void main (string[] args) {shareresourse resourse = ne W Shareresourse (); new Thread (new Product (resourse)) . Start (); // new Thread (new Consumer (resourse)). Start (); // }}
Synchronous threads, production consumption cases.