Java Concurrency tools -Semaphore, Exchanger

Semaphore can be considered broadly lock, shared lock,

Semaphore can be understood as a semaphore , the number of threads for the control resource can be accessed concurrently, a plurality of threads to ensure that a particular resource can be used reasonably. Semaphore is equivalent to a license, thread need to obtain a license by the acquire method, the thread can continue down, or only the block waiting in the method. After the completion of the implementation of business functions, we need release()a method to return the license, so that other threads can obtain a license to continue.

Semaphore can be used to do traffic control, especially public resources limited application scenarios, such as database connection. If there are a plurality of threads reading data, the data needs to be stored in the database, but only the maximum available database connections 10, this time need to control the number of threads Semaphore concurrent access to the database can be connected to only a maximum of 10 resource a. In limiting the use of resources application scenarios, Semaphore is particularly suitable.

It allows multiple threads to enter the critical section corresponding to a value of 1 when.

Here a simple example to illustrate the specific use Semaphore. So we have to simulate the same scenario. One day, the teacher needs the class 10 students fill out a form to the podium, but only teachers prepared five pens, therefore, can only guarantee the same time only five students can get a pen and fill out the form, the students did not get to pen only students can wait after the previous run, in order to get a pen to fill out the form. The following sample code:
public  class SemaphoreDemo { 

    // represents only 10 pens teacher 
    Private  static Semaphore semaphore = new new Semaphore ( . 5 ); 

    public  static  void main (String [] args) { 

        // represents 50 students 
        ExecutorService = Executors.newFixedThreadPool-Service (10 );
         for ( int I = 0; I <10; I ++ ) { 
            service.execute (() -> {
                 the try { 
                    . System.out.println (Thread.currentThread () getName () + "Get ready students .... pen .. " );
                    Semaphore.acquire (); 
                    System.out.println (Thread.currentThread () getName (). + "students get to pen" ); 
                    . System.out.println (Thread.currentThread () getName () + "fill out the form ing ..... " ); 
                    TimeUnit.SECONDS.sleep ( 3 );
                    semaphore.release (); 
                    System.out.println (Thread.currentThread (). getName () +" to fill out the form, return the pen !!! !!! " ); 
                } the catch (InterruptedException E) { 
                    e.printStackTrace (); 
                } 
            }); 
        } 
        service.shutdown (); 
    }

} 
The output: 

the pool -1-the Thread-1   students get ready pen ...... 
the pool -1-the Thread-1   students get to pen 
the pool -1-the Thread-1   Fill out the form ..... ING 
the pool -1 -thread-2   students get ready pen ...... 
the pool -1-the Thread-2   students get to pen 
the pool -the Thread 2 -1-   fill out the form ..... ING 
the pool -1-the Thread-3   students get ready ...... pen 
the pool -1-Thread. 4-   students prepared acquired pen ...... 
the pool -1. 3-Thread-   students pen acquired 
the pool -1-Thread. 4-   students pen acquired 
the pool -l- thread-4   fill form ..... ING 
the pool -1. 3-Thread-   fill form ..... ING 
the pool-1-thread-5   students get ready pen ...... 
the pool -1-thread-5   students get to pen 
the pool -1-thread-5   filling out forms ..... ING 


the pool -1-the Thread-6   students get ready pen ...... 
the pool -1-the Thread-7   students get ready pen ...... 
the pool -1-the Thread-8   students get ready pen ...... 
the pool -1-the Thread-9   students get ready pen ...... 
the pool -1-the Thread-10   students get ready pen ...... 


the pool -1-the Thread-4   to fill out the form, return the pen! ! ! ! ! ! 
the pool -1-the Thread-9   students get to pen 
the pool -1-the Thread-9   fill out the form ..... ING 
the pool -1-the Thread-5   filling out the form, return the pen! ! ! ! ! ! 
the pool -1-Thread. 7-  Students get to pen 
the pool -1-the Thread-7   fill out the form ..... ING 
the pool -1-the Thread-8   students get to pen 
the pool -1-the Thread-8   Fill out the form ..... ING 
the pool -1-the Thread -1   filling out the form, return the pen! ! ! ! ! ! 
the pool -1-the Thread-6   students get to pen 
the pool -1-the Thread-6   Fill out the form ..... ING 
the pool -1-the Thread-3   Fill out the form, return the pen! ! ! ! ! ! 
the pool -1-the Thread-2   filled out the form, return the pen! ! ! ! ! ! 
the pool -1-the Thread-10   students get to pen 
the pool -1-the Thread-10   Fill out the form ..... ING 
the pool -1-the Thread-7   to fill out the form, return the pen! ! ! ! ! ! 
the pool -1-Thread. 9-    filled out the form, return the pen! ! ! ! ! !
the pool-1-thread-8   filling out the form, return the pen! ! ! ! ! ! 
the pool -1-the Thread-6   filled out the form, return the pen! ! ! ! ! ! 
the pool -1-the Thread-10 finish filling out forms, returned the pen! ! ! ! ! !
According to the results of the analysis output, Semaphore maximum number of licenses allowed is 5, which is the maximum allowed number of threads concurrently executing 5, it can be seen, the first five threads (the first five students) to get to the pen, then fill in table, and 6-10 five threads, due not obtain permission, you can only block waiting. When the thread pool-1-thread-4 after the release of the license, pool-1-thread-9 you can get permission to continue down the implementation. , Is the same reason the execution of other threads. Can be seen from this example, Semaphore used for concurrent access to a particular resource control is quite appropriate, if there is need for flow control business scenarios, can prioritize Semaphore.
 
Exchanger

For exchanging data between threads. It provides a synchronization point, in this synchronization point, two threads can exchange data with each other. These two threads to exchange data exchange method, if the first thread to execute exchange () method, which has been waiting for a second thread also performs exchange method, when two threads have reached the synchronization point, these two threads data can be exchanged, passing this thread produced data to each other.

Exchanger can be viewed as a two-way form of SynchronousQueue. Exchanger is useful in genetic algorithms and pipeline design applications.

Memory Consistency: For each pair of thread successfully exchange objects through Exchanger, each thread in subsequent operations happen-before exchange operation before () corresponding to another thread from the exchange () returns.

method:

1      // waiting for another thread to arrive at this switching point (unless the current thread is interrupted), and then transmitted to the given object to the thread, and the thread of the receiving object. 
2      public V Exchange (V X) throws InterruptedException
 . 3      // increase the timeout mechanism over a specified time, throw exception TimeoutException 
. 4      public V Exchange (V X, Long timeout, TimeUnit Unit) throws InterruptedException, TimeoutException

 





Link: https: //juejin.im/post/5aeec49b518825673614d183

Guess you like

Origin www.cnblogs.com/dingpeng9055/p/11303927.html