Java multi-thread Development ~~~ Use of the Multi-Condition Interface

Source: Internet
Author: User

Java multi-thread Development ~~~ Use of the Multi-Condition Interface

This may happen in multi-threaded development. That is, a thread needs another thread to meet certain conditions to continue running, or needs

It takes other threads to meet several conditions to run. For such multi-condition multi-thread concurrency, how can we control the relationship between various threads so that they can

If conflicts can be well handled, there will be no mutual problems. Next we will introduce the Condition interface provided by Java, which is well implemented.

This requirement.

The most typical example of this problem is the producer consumer model. When the buffer zone is full, the producer does not produce goods and knows that the buffer zone is free and consumes

When the buffer zone is 0, do not take the goods until the producer puts the goods into the buffer zone. Below we use the Conditon interface to achieve this requirement.


Package com. bird. concursey. charpet4;/*** First, let's implement a class that will simulate a text file. create a class namedFileMock with two attributes: a String array named content and int namedindex. they will store the content of the file and the line of the simulated file that willbe retrieved. * @ author bird * September 21, 2014 6:55:31 */public class FileMock {private String content []; private int index; /*** Implement the constructor of the class that initializes the content of the file withrandom characters. * @ param size * @ param length */public FileMock (int size, int length) {content = new String [size]; for (int I = 0; I <size; I ++) {StringBuilder buffer = new StringBuilder (length); for (int j = 0; j <length; j ++) {int indice = (int) (Math. random () * 255); buffer. append (char) indice);} content [I] = buffer. toString () ;}index = 0 ;}/ *** Implement the method hasMoreLines () that returns true if the file has more linesto process or false if we have achieved the end of the simulated file. * @ return */public boolean hasMoreLines () {return index <content. length;}/*** Implement the method getLine () that returns the line determined by the indexattribute and increases its value. * @ return */public String getLine () {if (this. hasMoreLines () {System. out. println ("Mock:" + (content. length-index); return content [index ++];} return null ;}}



Package com. bird. concursey. charpet4; import java. util. using list; import java. util. concurrent. locks. condition; import java. util. concurrent. locks. reentrantLock;/*** implement a class named Buffer that will implement the buffer shared by * producers and consumers. ** @ author bird September 21, 2014 6:58:13 */public class Buffer {private writable list
 
  
Buffer; private int maxSize; private ReentrantLock lock; private Condition lines; private Condition space; private boolean pendingLines;/*** Implement the constructor of the class. it initializes all the attributesdescribed previusly. * @ param maxSize */public Buffer (int maxSize) {this. maxSize = maxSize; buffer = new writable list
  
   
(); Lock = new ReentrantLock (); lines = lock. newCondition (); space = lock. newCondition (); pendingLines = true;}/*** Implement the insert () method. it has es String as a parameter and triesto store it in the buffer. first, it gets the control of the lock. when it has it, it thenchecks if there is empty space in the buffer. if the buffer is full, it cballs the await () method in the space condition to wait for free space. the thread will be woken upwhen another thread callthe signal () or signalAll () method in the spaceCondition. when that happens, the thread stores the line in the buffer and callsthe signallAll () method over the lines condition. as we'll see in a moment, thiscondition will wake up all the threads that were waiting for lines in the buffer. * @ param line */public void insert (String line) {lock. lock (); try {while (buffer. size () = maxSize) {space. await ();} buffer. add (line); System. out. printf ("% s: Inserted Line: % d \ n", Thread. currentThread (). getName (), buffer. size (); lines. signalAll ();} catch (InterruptedException e) {e. printStackTrace ();} finally {lock. unlock () ;}/ *** Implement the get () method. it returns the first string stored in the buffer. first, itgets the control of the lock. when it has it, it checks if there are lines in the buffer. if the buffer is empty, it callthe await () method in the lines condition to waitfor lines in the buffer. this thread will be woken up when another thread CILS thesignal () or signalAll () method in the lines condition. when it happens, themethod gets the first line in the buffer, callthe signalAll () method over thespace condition and returns String. * @ return */public String get () {String line = null; lock. lock (); try {while (buffer. size () = 0) & (hasPendingLines () {lines. await ();} if (hasPendingLines () {line = buffer. poll (); System. out. printf ("% s: Line Readed: % d \ n", Thread. currentThread (). getName (), buffer. size (); space. signalAll () ;}} catch (InterruptedException e) {e. printStackTrace ();} finally {lock. unlock ();} return line;}/*** Implement the setPendingLines () method that establishes the value of theattribute pendingLines. it will be called by the producer when it has no more linesto produce. * @ param pendingLines */public void setPendingLines (boolean pendingLines) {this. pendingLines = pendingLines;}/*** Implement the hasPendingLines () method. it returns true if there are more linesto be processed, or false otherwise. * @ return */public boolean hasPendingLines () {return pendingLines | buffer. size ()> 0 ;}}
  
 


package com.bird.concursey.charpet4;public class Producer implements Runnable {private FileMock mock;private Buffer buffer;public Producer(FileMock mock, Buffer buffer) {this.mock = mock;this.buffer = buffer;}/** * Implement the run() method that reads all the lines created in the FileMockobject and uses the insert() method to store them in the buffer. Once it finishes,use the setPendingLines() method to alert the buffer that it's not going togenerate more lines. */@Overridepublic void run() {buffer.setPendingLines(true);while(mock.hasMoreLines()) {String line = mock.getLine();buffer.insert(line);}buffer.setPendingLines(false);}}


package com.bird.concursey.charpet4;import java.util.Random;public class Consumer implements Runnable {private Buffer buffer;public Consumer(Buffer buffer) {this.buffer = buffer;}/** * Implement the run() method. While the buffer has pending lines, it tries to get oneand process it. */@Overridepublic void run() {while(buffer.hasPendingLines()) {String line = buffer.get();processLine(line);}}/** * Implement the auxiliary method processLine(). It only sleeps for 10 millisecondsto simulate some kind of processing with the line. * @param line */private void processLine(String line) {Random random = new Random();try {Thread.sleep(random.nextInt(100));} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) {FileMock fileMock = new FileMock(100, 10);Buffer buffer = new Buffer(20);Producer producer = new Producer(fileMock, buffer);Thread threadProducer = new Thread(producer, "Producer");Consumer consumers[] = new Consumer[3];Thread threadConsumers[] = new Thread[3];for(int i = 0; i < 3; i++) {consumers[i] = new Consumer(buffer);threadConsumers[i] = new Thread(consumers[i], "consumer " + i);}threadProducer.start();for(int i = 0; i < 3; i++) {threadConsumers[i].start();}}}


Note:

When a thread callthe await () method of a condition, it automatically frees the control of the lock, so that another thread can get it and begin the execution of the same, or another critical section protected by that lock.

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.