——-Android Training, Java training, look forward to communicating with you! ———-
An overview of the JDK1.5 characteristics of producer and consumer problems
Before JDK1.5, to address producer and consumer issues,
With the Synchronized synchronous +while+notify ();
However, this method is not safe, it is easy to get all the threads into an infinite waiting state.
So we switched to Notiyfyall (), to solve.
This solves the security problem, but there are still deficiencies and security risks.
The Notifyall method wakes up all threads in the thread pool,
It's not what we want!
Also, the sync sleeve synchronization is prone to deadlocks!
The display lock mechanism is provided in the JDK1.5, which solves the above problem perfectly.
It can only wake the other thread, not wake up the thread,
It also allows a lock to bind multiple objects!
Second, my Code –jdk1.5 new features to solve the problem
Let's take a look at the new features of JDK1.5 first!
It is also shown with 2 producer threads and 2 consumer threads.
Steps:
1 Lookup API, find condition interface and lock interface
2 Defining Resource Classes
3 Defining the Producer class
4 Defining consumer Classes
5 Defining Test Classes
6 Guide Pack
7 Checking for security issues
8 Testing
9 Analysis Summary
Import java.util.concurrent.locks.*;//I. Defining Resource Classes class Resource{ PrivateString name;//Product name Private int Count=1;//Product Code Private BooleanFlag =false;//Resource Monitor PrivateLock lock =NewReentrantlock ();//Create a lock object, note that there is only one lock. Note that lock is an interface and you cannot create objects directly PrivateCondition Condition_pro = Lock.newcondition ();//Create a condition instance to use with the lock instance, which the producer uses PrivateCondition Condition_con = Lock.newcondition ();//Establish a condition instance that is used with the lock instance for consumers to use //Set product name, product number increment, and print set result Public voidSet (String name) throws Interruptedexception {Lock.lock ();//producer thread acquires the lock. Replace the original synchronized Try{ while(flag)//When Resource Monitor is true, producer threads wait forCondition_pro.await ();//Producer thread waits, and throws Interruptedexception This. name = name;//Get Product nameSystem.out.println (Thread.CurrentThread (). GetName () +"is the producer thread that produces the name of the product:"+name+"Item Number:"+Count);Count++;//Product number self-incrementFlag =true;//Change the Resource Monitor to TrueCondition_con.signal ();//wake-up of consumer threads only}finally{Lock.unlock ();//Be sure to release the lock} }//Remove the product and show the product number taken out Public voidGet () throws Interruptedexception {Lock.lock ();//Consumer thread acquisition lock Try{ while(!flag)//If the resource Monitor is false, the consumer thread waits and throws InterruptedexceptionCondition_con.await (); System.out.println (Thread.CurrentThread (). GetName () +"is the consumer thread that consumes the product name as:"+name+"Product number: ..."+Count); Flag =false;//Change the resource Monitor to FalseCondition_pro.signal ();//wake-up producer thread only}finally{Lock.unlock ();//Be sure to release the lock} }}//Second, define the producer class class Producer implements Runnable{ PrivateResource R;//reference resource type variable R //Overloaded constructors to avoid building multiple objectsProducer (Resource R) { This. R = r; }//Overwrite the Run method Public voidRun () {Try{ while(true)//Let producers continue to produceR.set ("Product"); }Catch(Interruptedexception e) {//temporary non-processing for the benefit of observation results} }}//third, define consumer class class Consumer implements Runnable{ PrivateResource R;//reference resource type variable R //overloaded constructors, and producer threads use the same resource objectConsumer (Resource R) { This. R =r; }//Overwrite the Run method Public voidRun () {Try{ while(true)//Let consumers always take goodsR.get (); }Catch(Interruptedexception e) {//temporary non-processing, easy to observe} }}//Four, define test class class MyProducerConsumerDemo2 { Public Static voidMain (string[] args) {Resource r =NewResource ();//Establish resourcesProducer p =NewProducer (R);//Build a producerConsumer c=NewConsumer (R);//Build consumerThread TP1 =NewThread (P);//build producer thread 1Thread TP2 =NewThread (P);//Build producer thread 2Thread TP3 =NewThread (P);//Build producer thread 3Thread TC1 =NewThread (c);//Build consumer thread 1Thread TC2 =NewThread (c);//Build consumer thread 2Thread TC3 =NewThread (c);//Build consumer thread 3Tp1.start ();//Start producer thread 1Tp2.start ();//Start producer thread 2Tp3.start ();//Start producer thread 3Tc1.start ();//Start consumer thread 1Tc2.start ();//Start consumer thread 2Tc3.start ();//Start producer thread 3}}
The running result shows normal!
Iii. Analysis and summary JDK1.5 new features
JDK1.5 defines the locking mechanism for the display
The lock implementation provides a wider range of locking operations than is possible with synchronized methods and statements.
This implementation allows for a more flexible structure that can have very different properties and can support multiple related Condition objects.
Replace the sync operation synchronized with the lock interface
Replaces the Wait,notify,notifyall in object with the condition object
In this example, it is implemented to wake the other thread only, without waking the thread.
Implements a lock lock that binds two objects Condition_pro and Condition_con.
Attention:
Both lock and condition are interfaces, and you cannot create objects directly.
Creating a Lock object here takes advantage of the Reentrantlock class
Creating a Condition object takes advantage of the Newcondition method in the Reentrantlock class.
Reentrantlock a reentrant mutex lock with the use of synchronized methods and statements
The implicit monitor lock accessed has the same basic behavior and semantics, but is more powerful.
Dark Horse Programmer _ Diary 18_java Multithreading (eight)--producer consumer problem JDK1.5 characteristics