Java Concurrency tool Class (iv) exchanger of exchanging data between threads

Source: Internet
Author: User

Brief introduction

Exchanger (the Exchange) is a tool class for collaboration between threads. The exchanger is used for data exchange between threads. It provides a synchronization point at which two threads at this synchronization point can exchange data between each other. These two threads Exchange data through the Exchange method, and if the first thread executes the Exchange method, it waits for the second thread to also execute exchange, and when two threads reach the synchronization point, the two threads can exchange data and pass the data produced by the thread to each other.

Exchanger's Application Scenario

1,exchanger can be used in genetic algorithms where two people are chosen as mating objects, and the data for two people is exchanged, and 2 mating results are obtained using cross-rules.
2,exchanger can also be used for proofreading work. For example, we need to paper silver flow through manual input into the electronic bank water, in order to avoid errors, the use of AB Gang two people to enter, entered into Excel, the system needs to load the two Excel, and the two Excel data to proofread, to see if the input is consistent. The code is as follows:

1  Public classExchangertest {2 3     Private Static FinalExchanger<string> exgr =NewExchanger<string>();4 5     Private StaticExecutorservice ThreadPool = Executors.newfixedthreadpool (2);6 7      Public Static voidMain (string[] args) {8 9Threadpool.execute (NewRunnable () {Ten @Override One              Public voidrun () { A                 Try { -String a = "Bank water a";//a input bank data - Exgr.exchange (A); the}Catch(interruptedexception e) { -                 } -             } -         }); +  -Threadpool.execute (NewRunnable () { + @Override A              Public voidrun () { at                 Try { -String B = "bank pipelining B";//b input Bank data -String A = Exgr.exchange ("B"); -System.out.println ("A and B data are consistent:" + a.equals (b) + ", a entry is:" -+ A + ", B entry is:" +B); -}Catch(interruptedexception e) { in                 } -             } to         }); +  - Threadpool.shutdown (); the  *     } $}

3, this class is very useful in the case of problems similar to producers and consumers. To a very classic concurrency problem: You have the same data buffer, one or more data producers, and one or more data consumers. Just exchange classes can only synchronize 2 threads, so you can only use this class when you have only one producer and one consumer in your producer and consumer issues.

In this guide, you will learn how to use the Exchanger class to solve problems for producers and consumers with only one producer and one consumer.

Follow these steps to implement the following example:

1  Packagetool;2 Importjava.util.List;3 ImportJava.util.concurrent.Exchanger;4 5 //1. First, start by implementing producer. Create a class named producer and be sure to implement the Runnable interface. 6  Public classProducerImplementsRunnable {7 8 //2. Declare the List<string> object, named buffer. This is the type of data to be exchanged with each other. 9 PrivateList<string>buffer;Ten  One //3. Declare the exchanger<list<string>>; object, named Exchanger. This exchanger object is used to synchronize producer and consumer.  A Private FinalExchanger<list<string>>Exchanger; -  - //4. Implement the constructor of the class and initialize the 2 properties.  the  PublicProducer (list<string> buffer, exchanger<list<string>>Exchanger) { -  This. Buffer =buffer; -  This. Exchanger =Exchanger; - } +  - //5. Implement the Run () method. Within the method, implement 10 interchanges.  + @Override A  Public voidrun () { at intCycle = 1; -  for(inti = 0; I < 10; i++) {System.out.printf ("producer:cycle%d\n"), cycle); -  - //6. In each loop, add 10 strings to buffer.  -  for(intj = 0; J <10; J + +) { -String message = "Event" + ((I * 10) +j); inSystem.out.printf ("Producer:%s\n", message); - buffer.add (message); to } +  - //7. Call the Exchange () method to exchange data with consumer. This method may throw interruptedexception exceptions, plus processing code.  the Try { *Buffer =exchanger.exchange (buffer); $}Catch(interruptedexception e) {Panax Notoginseng e.printstacktrace (); - } theSystem.out.println ("Producer:" +buffer.size ()); +cycle++; A } the } +}
1 //8. Now, to implement consumer. Create a class named consumer and be sure to implement the Runnable interface. 2  Packagetool;3 Importjava.util.List;4 ImportJava.util.concurrent.Exchanger;5  Public classConsumerImplementsRunnable {6 7 //9. Declare the List<string> object named buffer. This object type is used to exchange with each other. 8 PrivateList<string>buffer;9 Ten //10. Declare a Exchanger<list<string>> object named Exchanger. Used to synchronize producer and consumer.  One Private FinalExchanger<list<string>>Exchanger; A  - //11. Implement the constructor of the class and initialize the 2 properties.  -  PublicConsumer (List<string>buffer, exchanger<list<string>>Exchanger) { the  This. Buffer =buffer; -  This. Exchanger =Exchanger; - } -  + //12. Implement the Run () method. Within the method, 10 interchanges are implemented.  - @Override +  Public voidrun () { A intCycle = 1; at  for(inti = 0; I < 10; i++) { -System.out.printf ("Consumer:cycle%d\n", cycle); -  - //13. In each loop, first call the Exchange () method to synchronize with the producer. Consumer needs to consume data. This method may throw interruptedexception exceptions, plus processing code.  - Try { -Buffer =exchanger.exchange (buffer); in}Catch(interruptedexception e) {e.printstacktrace (); - } to  + //14. Write the 10 string in buffer that producer sent to the console and remove it from the buffer, leaving it blank. System.out.println ("Consumer:" + buffer.size ()); -  for(intj = 0; J <10; J + +) { theString message = Buffer.get (0); *System.out.println ("Consumer:" +message); $Buffer.remove (0);Panax Notoginseng } -cycle++; the}
1 //15. Now, the main class of the implementation example is by creating a class called core and adding the main () method. 2  Packagetool;3 Importjava.util.ArrayList;4 mport Java.util.List;5 ImportJava.util.concurrent.Exchanger;6 7  Public classCore {8  Public Static voidMain (string[] args) {9 Ten //16. Create 2 buffers. Used for producer and consumer, respectively. OneList<string> Buffer1 =NewArraylist<string>(); Alist<string> buffer2 =NewArraylist<string>(); -  - //17. Create a Exchanger object to synchronize producer and consumer.  theExchanger<list<string>> Exchanger =NewExchanger<list<string>>(); -  - //18. Create producer objects and consumer objects.  -Producer Producer =NewProducer (buffer1, exchanger); +Consumer Consumer =NewConsumer (buffer2, exchanger); -  + //19. Create a thread to execute producer and consumer and start the thread.  AThread Threadproducer =NewThread (producer); atThread Threadconsumer =NewThread (consumer); Threadproducer.start (); - Threadconsumer.start (); -}

The consumer starts with a blank buffer, and then calls exchanger to synchronize with the producer. Because it requires data to consume. The producer also starts with a blank buffer, then creates 10 strings, saves it to buffer, and synchronizes with the consumer using exchanger.

Here, 2 threads (producer and consumer threads) are in the exchanger and exchange data types, so when the consumer returns from the Exchange () method, it has 10 strings inside the buffer. When the producer returns from the Exchange () method, it has a blank buffer to re-write. This operation repeats 10 times.

As you perform the example, you will find out how producers and consumers are concurrently performing tasks and how they exchange buffers at each step. This happens as with other synchronization tools, and the first call to the Exchange () method goes into hibernation until the other thread reaches it.

Other methods

If one of the two threads does not reach the Exchange method, it waits, and if you are concerned about a special situation and avoid waiting, you can use Exchange (V data, long time, Timeunit unit) to set the maximum wait duration.

---v is the type of argument that declares phaser (in the example, List). This thread sleeps until another thread arrives and interrupts it, or a specific time passes. The Timeunit class has several constants: Days, HOURS, microseconds, MILLISECONDS, MINUTES, nanoseconds, and SECONDS.

Reference: The Art of Java concurrent programming

Java Concurrency tool Class (iv) exchanger of exchanging data between threads

Related Article

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.