Semaphore with the tools Exchanger Java Concurrency

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/ThinkWon/article/details/102557034

Semaphore control concurrent access to resources

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.

Semaphore look at the main method of the following:

//获取许可,如果无法获取到,则阻塞等待直至能够获取为止
void acquire() throws InterruptedException 

//同acquire方法功能基本一样,只不过该方法可以一次获取多个许可
void acquire(int permits) throws InterruptedException

//释放许可
void release()

//释放指定个数的许可
void release(int permits)

//尝试获取许可,如果能够获取成功则立即返回true,否则,则返回false
boolean tryAcquire()

//与tryAcquire方法一致,只不过这里可以指定获取多个许可
boolean tryAcquire(int permits)

//尝试获取许可,如果能够立即获取到或者在指定时间内能够获取到,则返回true,否则返回false
boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException

//与上一个方法一致,只不过这里能够获取多个许可
boolean tryAcquire(int permits, long timeout, TimeUnit unit)

//返回当前可用的许可证个数
int availablePermits()

//返回正在等待获取许可证的线程数
int getQueueLength()

//是否有线程正在等待获取许可证
boolean hasQueuedThreads()

//获取所有正在等待许可的线程集合
Collection<Thread> getQueuedThreads()

Further, in the configuration of the method Semaphore also supports fairness specify whether the default non fairness, this is to ensure that the throughput.

one example

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 {

    //表示老师只有5支笔
    private static Semaphore semaphore = new Semaphore(5);

    public static void main(String[] args) {

        //表示10个学生
        ExecutorService service = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            service.execute(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + "  同学准备获取笔......");
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "  同学获取到笔");
                    System.out.println(Thread.currentThread().getName() + "  填写表格ing.....");
                    TimeUnit.SECONDS.sleep(3);
                    semaphore.release();
                    System.out.println(Thread.currentThread().getName() + "  填写完表格,归还了笔!!!!!!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        service.shutdown();
    }

}

Output

pool-1-thread-2  同学准备获取笔......
pool-1-thread-4  同学准备获取笔......
pool-1-thread-5  同学准备获取笔......
pool-1-thread-3  同学准备获取笔......
pool-1-thread-3  同学获取到笔
pool-1-thread-1  同学准备获取笔......
pool-1-thread-3  填写表格ing.....
pool-1-thread-9  同学准备获取笔......
pool-1-thread-8  同学准备获取笔......
pool-1-thread-5  同学获取到笔
pool-1-thread-5  填写表格ing.....
pool-1-thread-4  同学获取到笔
pool-1-thread-4  填写表格ing.....
pool-1-thread-6  同学准备获取笔......
pool-1-thread-2  同学获取到笔
pool-1-thread-2  填写表格ing.....
pool-1-thread-10  同学准备获取笔......
pool-1-thread-7  同学准备获取笔......
pool-1-thread-1  同学获取到笔
pool-1-thread-1  填写表格ing.....
pool-1-thread-4  填写完表格,归还了笔!!!!!!
pool-1-thread-10  同学获取到笔
pool-1-thread-10  填写表格ing.....
pool-1-thread-7  同学获取到笔
pool-1-thread-7  填写表格ing.....
pool-1-thread-6  同学获取到笔
pool-1-thread-6  填写表格ing.....
pool-1-thread-9  同学获取到笔
pool-1-thread-9  填写表格ing.....
pool-1-thread-5  填写完表格,归还了笔!!!!!!
pool-1-thread-8  同学获取到笔
pool-1-thread-3  填写完表格,归还了笔!!!!!!
pool-1-thread-1  填写完表格,归还了笔!!!!!!
pool-1-thread-2  填写完表格,归还了笔!!!!!!
pool-1-thread-8  填写表格ing.....
pool-1-thread-7  填写完表格,归还了笔!!!!!!
pool-1-thread-6  填写完表格,归还了笔!!!!!!
pool-1-thread-10  填写完表格,归还了笔!!!!!!
pool-1-thread-8  填写完表格,归还了笔!!!!!!
pool-1-thread-9  填写完表格,归还了笔!!!!!!

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-4after the release of the license, pool-1-thread-10you 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.

Inter-thread data exchange tool Exchanger

Exchanger is a utility class for collaboration between threads, for exchanging data between two threads. It provides a synchronization point of exchange, in this synchronization point two threads can exchange data. Data exchange is achieved through the exchange method, if a thread is executed first exchange method, then it will wait for another thread synchronization also performs exchange method, this time on two threads have reached a synchronization point, two threads can exchange data .

Exchanger except a constructor with no arguments, the main method is very simple:

//当一个线程执行该方法的时候,会等待另一个线程也执行该方法,因此两个线程就都达到了同步点
//将数据交换给另一个线程,同时返回获取的数据
V exchange(V x) throws InterruptedException

//同上一个方法功能基本一样,只不过这个方法同步等待的时候,增加了超时时间
V exchange(V x, long timeout, TimeUnit unit)
    throws InterruptedException, TimeoutException 

one example

Exchanger is easy to understand, here a simple example under its specific use. Let's simulate such a scenario, youthful in high school, during school, boys often give the hallway send a love letter to their favorite girl, I believe we have done such a thing now. Boys will first girl classroom door, then wait for the girl out of the classroom there is a synchronization point, and then exchange the token to each other, that is, exchange data with each other. Now, on to simulate this scenario.

public class ExchangerDemo {
    private static Exchanger<String> exchanger = new Exchanger();

    public static void main(String[] args) {

        //代表男生和女生
        ExecutorService service = Executors.newFixedThreadPool(2);

        service.execute(() -> {
            try {
                //男生对女生说的话
                String girl = exchanger.exchange("我其实暗恋你很久了......");
                System.out.println("女孩儿说:" + girl);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        service.execute(() -> {
            try {
                System.out.println("女生慢慢的从教室你走出来......");
                TimeUnit.SECONDS.sleep(3);
                //男生对女生说的话
                String boy = exchanger.exchange("我也很喜欢你......");
                System.out.println("男孩儿说:" + boy);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }
}

Output

女生慢慢的从教室你走出来......
男孩儿说:我其实暗恋你很久了......
女孩儿说:我也很喜欢你......

This example is very simple, and very able to explain the basic use Exchanger. When two threads are calling to reach the synchronization point exchange process, the two threads can exchange data with each other.

Guess you like

Origin blog.csdn.net/ThinkWon/article/details/102557034