Description of producer and consumer issues
Through, we can find:
Producers and consumers are using the same resource (meat buns)
Therefore, when using threads, these two types of locks are also the same lock (in order to avoid thread safety problems)
Example: entry and acquisition of student information
* Resource class: Student
* Set student data: Setthread (producer)
* Access to Student data: getthread (consumer)
* Test class: Studentdemo
* Resource class: Student
1 Public class Student {2 3 String name; 4 int Age ; 5 }
* Set student data: Setthread (producer)
Public classSetthreadImplementsRunnable {Private intx = 0; //because Setthread and getthread two classes use the same resource//So, when you create a resource object and pass it to another class by constructing the method PrivateStudent S; PublicSetthread (Student s) { This. S =s; } Public voidrun () {//input information (producer) while(true) { //Lock , and Setthread and getthread two classes use the same lock, so the object of the lock is the resource object s synchronized(s) {if(x% 2 = = 0) {S.name= "Zhang San"; S.age= 23; } Else{s.name= "John Doe"; S.age= 24; } x++; } } }}
* Access to Student data: getthread (consumer)
1 Public classGetThreadImplementsRunnable {2 3 PrivateStudent S;4 PublicGetThread (Student s) {5 This. S =s;6 }7 Public voidrun () {8 //access to information consumers9 //lock object, same as SetthreadTen while(true){ One synchronized(s) { ASystem.out.println (S.name + "--" +s.age); - } - } the - } - -}
* Test class: Studentdemo
1 Public classStudentdemo {2 3 4 Public Static voidMain (string[] args) {5 6 //Create a Resource object7Student s =NewStudent ();8 9 //creating objects for entering and retrieving classesTenSetthread st =NewSetthread (s); OneGetThread GT =NewGetThread (s); A - //To create a thread object -Thread T1 =NewThread (ST); theThread t2 =NewThread (GT); - - //Start Thread - T1.start (); + T2.start (); - + } A at}
Results:
Producer Setthread class continuously input student information (can be regarded as the continuous production of steamed buns? )
But the consumer GetThread class then unceasingly obtains the input information (buys the steamed bun? )
Of course, the ideal state is the producer produces 1, the consumer immediately consumes 1 ....
But, here is not this ideal state, the two still have to seize the CPU resources, if the production of more, then piled up and other consumers.
If consumers seize more resources, they have been consuming the same bun?
Java 22-16 Multi-thread producer and consumer issues