PackageCom.xiaoju.demo;/*** Hello world! * thread communication and thread safe sample!! **/ Public classApp { Public Static voidMain (string[] args) {System.out.println ("Hello world!" ); //Thread CommunicationQ q =NewQ (); NewThread (NewProducer (q)). Start (); NewThread (NewConsumer (q)). Start (); }}classProducerImplementsrunnable{q q; PublicProducer (q q) { This. q=Q; } Public voidrun () {intI=0; while(true){ if(i==0) {Q.put ("Zhangsan", "male"); } Else{q.put ("Lisi", "female"); } I= (i+1)%2; } }}classConsumerImplementsrunnable{q q; PublicConsumer (q q) { This. q=Q; } Public voidrun () { while(true) {q.get (); } }}classq{PrivateString name= "Unknown"; PrivateString sex= "Unknown"; Private BooleanBfull=false; Public synchronized voidput (String name,string sex) {if(bfull) {Try{wait (); } Catch(Exception e) {}} This. name=name; Try{thread.sleep (1);}Catch(Exception e) {} This. sex=sex; Bfull=true; Notify (); } Public synchronized voidget () {if(!bfull) { Try{Wait ();}Catch(Exception e) {}} System.out.print (name); System.out.println (":"+sex); Bfull=false; Notify (); }}
Thread communication and thread-safe instances