java-concurrency-Protecting code blocks

Source: Internet
Author: User

Threads often need to coordinate their actions, and the most common method of coordination is to protect a block of code that starts with a condition and evaluates to true to begin execution.

Suppose a method Guradedjoy must wait until the variable joy is set by another thread before it can start executing, such a method, theoretically a simple loop until the condition is satisfied, but such a cycle is a waste of resources, because the waiting time is constantly executing.

 Public void Guardedjoy () {    //while    (!  Joy) {}    System.out.println ("Joy has been achieved!" );}

A more efficient method is to call the wait method of the object class to pause the current thread, and the wait method's call is returned only if another thread has notified that a particular event has occurred, but that particular event is not necessarily the event that the thread is waiting for:

 Public synchronized void Guardedjoy () {    //   This protection usage is only used for a specific event loop once and can not be a waiting event while    (!  Joy) {        try  {            wait ();         Catch (Interruptedexception e) {}    }    System.out.println ("Joy and efficiency have been achieved!" );}

Note: Use the Wait method in a loop that tests for a wait condition, and do not assume that the interrupt is for the condition you are waiting for, or that the waiting condition is still true.
Like other methods of suspending execution, the wait method can throw interruptexception, and when a thread calls the wait method of an object, the thread must have a built-in lock on the object (as in the previous example, the Guardedjoy method is the synchronous method), or an error will be thrown. Calling the wait method in a synchronous method is a simple way to request a built-in lock.

When the wait method is called, the thread releases the lock and pauses execution. In the next time, another thread will request the same lock and invoke the Notifyall of the object class, notifying all threads waiting for the lock that something important has already happened. When the second thread releases the lock, the first thread requests the lock and returns from the calling wait method.

Note: There is another method of notification, notify, that the method wakes only one thread, because the Notify method cannot specify the thread to be awakened, this method is only useful in large-scale parallel programs, that is, there are many threads in the program doing the same thing, such programs, Don't worry about which thread is waking up.

Use the block of protection to create a simple producer-consumer program that shares data between two threads, producers generate data, and consumers process data, and two threads communicate through a shared object. Coordination between threads is important: Consumers cannot retrieve data between producers, and producers cannot pass on new data until they are retrieved by the consumer.

The following defines the object that a class uses to create traffic:

 Public classDrop {//information that producers send to consumers    PrivateString message; //true if the consumer needs to wait for the consumer to send the message, False if the consumer needs to wait for the message to be received    Private BooleanEmpty =true;  Public synchronizedString Take () {//wait for information to be available         while(empty) {Try{wait (); } Catch(Interruptedexception e) {}}//Conversion StatusEmpty =true; //notifies producer that information has been retrievedNotifyall (); returnmessage; }     Public synchronized voidput (String message) {//wait for information to be retrieved         while(!empty) {            Try{wait (); } Catch(Interruptedexception e) {}}//Conversion StatusEmpty =false; //Store message.         This. Message =message; //notify consumers that the status has changedNotifyall (); }}

Define a producer class, send a series of familiar information, the string "Done" indicates that all the information has been sent, in order to simulate the real program, the intermittent producer class that sends the message will pause for a random period of time.

//import random classes to produce a random numberImportJava.util.Random; Public classProducerImplementsRunnable {Privatedrop drop;  PublicProducer (Drop drop) { This. Drop =drop; }     Public voidrun () {String importantinfo[]= {            "Mares Eat oats",            "Does Eat oats",            "Little Lambs eat Ivy",            "A kid'll eat Ivy too"        }; Random Random=NewRandom ();  for(inti = 0; I<importantinfo.length; I++) {drop.put (importantinfo[i]); Try {//pause for a random period of timeThread.Sleep (Random.nextint (5000)); } Catch(Interruptedexception e) {}} drop.put ("Done"); }}

The consumer thread definition is defined by the consumer class and simply retrieves and outputs information until it is retrieved to "done", and the thread also intermittently pauses for a random time:

ImportJava.util.Random; Public classConsumerImplementsRunnable {Privatedrop drop;  PublicConsumer (Drop drop) { This. Drop =drop; }     Public voidRun () {random random=NewRandom ();  for(String message =Drop.take (); ! Message.equals ("Done"); Message=Drop.take ()) {System.out.format ("MESSAGE RECEIVED:%s%n", message); Try{thread.sleep (Random.nextint (5000)); } Catch(Interruptedexception e) {} }}}

Finally, define a main thread in an arbitrary class to ProducerConsumerExample create the information object and start the producer and consumer threads.

 Public class producerconsumerexample {    publicstaticvoid  main (string[] args) {         New  Drop ();        ( new Thread ( new Producer)). Start ();        ( new Thread ( new Consumer)). Start ();}    }

The drop class above was created to demonstrate the use of protected code blocks, and the Java Collections Framework (Java framework) provides a class of data sharing that provides a rich set of functionality so that you do not have to define your own classes.

  

java-concurrency-Protecting code blocks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.