Java Concurrency series of Semaphore Detailed

basic introduction

Our hotel, for example, assume that the hotel only three seats, three seats are initially empty. Then if at the same time to three guests, waiters allow people to go where they dine, and then say No outside seating. Later, guests must wait at the door until the guest leaves. At this time, if there is a guest to leave, the waiter told the guests can dine come in, and if guests leave, then they can come to dine, and so forth.
In this restaurant, the seats are public resources, everyone is like a thread, the waiter is the role played by semaphore. Semaphore is a non-negative integer representing the number of available current public resources (in the above example seat analog signal the amount of free can be used), when a thread is about to use the common resource (can be used to suit those in the above example thread), we must first see the semaphore if the semaphore value is greater than 1, it is decremented by 1, and then to occupy public resources. If the semaphore is 0, the thread will own blocked until another thread releases public resources.

1, a brief introduction Semaphore

a, can be used to control the number of threads simultaneously access a particular resource, in order to achieve the coordination of worker threads.
b, maintains a virtual pool of resources, if the license is 0 thread blocks until a license is greater than zero time and have the opportunity to obtain a license.
c, internal static inner classes are also fair locks, lock unfair access to resources.

2, Semaphore method

a, public Semaphore (int permits) ; // create a license number of a given semaphore object, and the default access to resources in a fair and non-lock mode
b, public Semaphore (int permits, boolean fair); // create a given license semaphore object number, and whether it is fair fair manner determined by the incoming value of Boolean parameter
c, public void acquire (); // this semaphore acquired a license, the license when the number is less than zero, then the block waiting
d, public void acquire (int permits); // this semaphore obtain permits licenses, when the number of licenses is less than zero, then the block waiting, but when the thread is blocked waiting awakened found to be interrupted, then it will throw an exception InterruptedException
e, public void acquireUninterruptibly (int permits); this semaphore obtain permits licenses, when the number of licenses is less than zero, then the block waiting, but when the thread is blocked waiting awakened found to be interrupted, then it will not throw InterruptedException anomaly
f, public void release (); // a release permission
g, public void release (int permits ); release Permits licenses
than just a list of the main To the method name, explained in detail, Semaphore class above all comments. Not one tired out.

As a simple example, help us to deepen the impression

/**
 * @author shuliangzhao
 * @Title: SemaPhoreTest
 * @ProjectName design-parent
 * @Description: TODO
 * @date 2019/6/5 22:50
 */
public class SemaPhoreTest {

    private Semaphore semaphore = new Semaphore(3);

    class TaskThread implements Runnable{

        private int id;

        public TaskThread(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
                System.out.println("Thread " + id + " is working");
                Thread.sleep(2000);
                semaphore.release();
                System.out.println("Thread " + id + " is over");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        SemaPhoreTest semaPhoreTest = new SemaPhoreTest();
        /*for (int i = 0;i<6;i++) {
            Thread thread = new Thread(semaPhoreTest.new TaskThread(i));
            thread.start();
        }*/
        ExecutorService executorService = Executors.newCachedThreadPool();//同步队列线程
        executorService.submit(semaPhoreTest.new TaskThread(1));
        executorService.submit(semaPhoreTest.new TaskThread(2));
        executorService.submit(semaPhoreTest.new TaskThread(3));
        executorService.submit(semaPhoreTest.new TaskThread(4));
        executorService.submit(semaPhoreTest.new TaskThread(5));
        executorService.submit(semaPhoreTest.new TaskThread(6));
        executorService.submit(semaPhoreTest.new TaskThread(7));
        executorService.shutdown();
    }
}

operation result


4327221-37b8f2b2188c2d73.png
image.png

Reproduced in: https: //www.jianshu.com/p/91bb105a98f0

Guess you like

Origin blog.csdn.net/weixin_33881041/article/details/91278903