Example: Info.java
1 Public classInfo {2 3 PrivateString name= "Sir Wang";4 PrivateString content= "Java instructor";5 PublicString GetName () {6 returnname;7 }8 Public voidsetName (String name) {9 This. Name =name;Ten } One PublicString getcontent () { A returnContent; - } - Public voidsetcontent (String content) { theContent =content; - } - -}
Example: Producer
1 Public classProducerImplementsRunnable {2 3 PrivateInfo info =NULL;4 5 PublicProducer (Info info) {6 This. info =info;7 }8 @Override9 Public voidrun () {Ten One BooleanFlag =false; A for(inti = 0; I < 50; i++) { - if(flag) { - This. Info.setname ("Sir Wang"); the Try { -Thread.Sleep (90); -}Catch(interruptedexception e) { - e.printstacktrace (); + } - This. Info.setcontent ("Java instructor"); +Flag =false; A}Else { at This. Info.setname ("Cheung Sir"); - Try { -Thread.Sleep (90); - -}Catch(interruptedexception e) { - e.printstacktrace (); in } - This. Info.setcontent ("C # Instructor"); toFlag =true; + } - } the } *}
Example: Consumer
1 Public classConsumerImplementsRunnable {2 3 PrivateInfo info =NULL;4 5 PublicConsumer (Info info) {6 This. info =info;7 }8 9 @OverrideTen Public voidrun () { One for(inti = 0; I < 50; i++) { A Try { -Thread.Sleep (100); -}Catch(interruptedexception e) { the e.printstacktrace (); - } -System.out.println ( This. Info.getname () + "--" -+ This. Info.getcontent ()); + } - } + A}
Example: The Keynote method
1 Public classThreadcasedemo {2 3 Public Static voidMain (string[] args) {4Info i =NewInfo ();5Producer Pro =NewProducer (i);6Consumer con =NewConsumer (i);7 NewThread (PRO). Start ();8 NewThread (Con). Start ();9 }Ten}
Example: Running results
Zhang Sir-->java Lecturer
Wang Sir-->java Lecturer
Wang Sir-->c# Lecturer
Zhang Sir-->java Lecturer
Wang Sir-->c# Lecturer
Zhang Sir-->java Lecturer
Wang Sir-->c# Lecturer
Zhang Sir-->java Lecturer
Wang Sir-->c# Lecturer
Zhang Sir-->java Lecturer
Wang Sir-->java Lecturer
Wang Sir-->java Lecturer
Wang Sir-->java Lecturer
Wang Sir-->java Lecturer
Wang Sir-->java Lecturer
Wang Sir-->java Lecturer
The operation of the thread is determined by the CPU scheduling, there is no negligible uncertainty, so in the use of threads, there are 2 problems:
1. Assuming that the producer Line Cheng Gang adds the name of the information to the data storage space and does not include the content of that information, the program switches to the consumer thread, and the consumer thread will associate the name of the information with the contents of the previous message. (Sync issue)
2. The producer has placed several times of data before the consumer begins to fetch the data, or after the consumer has completed the data, it has not waited until the producer has put in the new data and has repeatedly taken out the data that has been taken.
Producer and consumer of threading operations