One semaphore has and only 3 operations, and they are all atomic: Initialize, increase, and decrease
Increase can be unblocked for a process;
The reduction allows a process to enter the block.
Semaphores maintain a license set and, if necessary, block each thread before obtaining a license:
A given number of licenses are obtained from this semaphore, and threads are blocked until these licenses are available.
acquireuninterruptibly (int permits) {}
Each release () adds a license that may release a blocked fetch.
Semaphore only counts the number of available licenses and takes action accordingly.
How do I get Semaphore objects?
Public Semaphore (int Permits,boolean Fair)
Permits: Initialize the number of licenses available.
Fair: True if the semaphore is guaranteed to be granted in FIFO order at the time of requisition, otherwise false;
How do I get a license from the semaphore?
public void Acquire () throws Interruptedexception
How do I release a license and return the semaphore?
public void Release ()
code example:
20 people went to the bank to deposit, but the bank only two office counters, there are seats to go up to save money, there is no vacancy can only go to wait in line
Package Com.xhj.thread;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.semaphore;/** * Application of thread semaphore Semaphore * * @author Xiehejun * */public class Semaphorethread {privat e int a = 0; /** * Bank Savings class */class Bank {private int account = 100; public int Getaccount () {return account; ' public void ' Save (int money) {account + = money; }}/** * thread execution class, save 10 dollars per time */class Newthread implements Runnable {private Bank bank; Private Semaphore Semaphore; Public Newthread (Bank Bank, Semaphore Semaphore) {this.bank = Bank; This.semaphore = semaphore; } @Override public void Run () {int b = a++; if (semaphore.availablepermits () > 0) {System.out.println ("thread" + B + "Start, enter the bank, have the location to save money immediately"); } else {System.out.println ("thread" + B + "start, into the bank, no place, to wait in line waiting "); } try {semaphore.acquire (); Bank.save (10); System.out.println (b + "account balance:" + bank.getaccount ()); Thread.Sleep (1000); SYSTEM.OUT.PRINTLN ("thread" + B + "Saving up, leaving the bank"); Semaphore.release (); } catch (Interruptedexception e) {e.printstacktrace (); }}}/** * Create thread, call internal class, start saving * * public void Usethread () {Bank Bank = new Bank (); Define 10 new numbers Semaphore Semaphore = new Semaphore (2); Create a cache thread pool Executorservice es = Executors.newcachedthreadpool (); Create 20 threads for (int i = 0; i < i++) {//execute a thread es.submit (new Newthread (ban K, Semaphore)); }//Close thread pool Es.shutdown (); Obtain two licenses from the semaphore and block the thread semaphore.acquireuninterruptibly (2) until the license is obtained; System.out.println ("to the point, staff to eat"); ReleaseTwo licenses and returns them to the semaphore semaphore.release (2); } public static void Main (string[] args) {semaphorethread test = new Semaphorethread (); Test.usethread (); }}
thinking:
In many cases, there may be multiple threads that require access to a small number of resources. It is assumed that several threads are running on the server that answer client requests. These threads need to connect to the same database, but at any one time
Only a certain number of database connections can be obtained. How will you be able to effectively allocate these fixed number of database connections to a large number of threads?
Answer:1. Add a synchronous lock to the method to ensure that only one person can call this method at the same time, all other threads are queued, but in this case, even if you have 10 database links, there is always only one in the
Use status. This will greatly waste the system resources, and the operating efficiency of the system is very low.
2. Another approach, of course, is to use semaphores , which can greatly improve efficiency and performance by using the same number of semaphore licenses as the number of available connections in the database.
Java thread Synchronization (iii) Semaphore