Java notes-understanding and using semaphores Semaphore, and using emaphore

Source: Internet
Author: User

Java notes-understanding and using semaphores Semaphore, and using emaphore

Use of java Semaphore semaphores:

 

In javaSemaphores Semaphore.


The Semaphore class is a counting Semaphore and must be released by the thread that obtains it,
It is usually used to limit the number of threads that can access certain resources (physical or logical.


A semaphore has only three types of operations, all of which are atomic: initialization, increase, and decrease.
Added to remove blocking for a process;
Reducing can cause a process to become congested.

-- If you want To reprint this article, please indicate the reprint address "http://www.cnblogs.com/XHJT/p/3910406.html" thank you --

Semaphores maintain a license set. If necessary, each thread is blocked before the license is obtained:
// Obtain a certain number of licenses from this semaphore and block the threads until these licenses are provided.
AcquireUninterruptibly (int permits ){}
EveryRelease ()Add a license to release a blocked recipient.
Semaphore only counts available license numbers and takes corresponding actions.

How to obtain the Semaphore object?
Public Semaphore (int permits, boolean fair)
Permits: number of licenses available for initialization.
Fair: If the semaphore is licensed in FIFO order during the collection, the value is true; otherwise, the value is false;

How can I obtain a license from a semaphore?
Public void acquire () throws InterruptedException

 

How do I release a license and return a semaphore?
Public void release ()

Code example:
20 people go to the bank for deposits, but the bank has only two Office counters. If there is space, they go up to save money. If there is no space, they can only wait in queue.

Package com. xhj. thread; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. semaphore;/*** use of thread semaphores Semaphore ** @ author XIEHEJUN **/public class SemaphoreThread {private int a = 0; /*** Bank deposit class */class Bank {private int account = 100; public int getAccount () {return account;} public void save (int money) {account + = money ;}}/*** thread execution class, with 10 yuan saved each time */class NewThread implements Runnable {private Bank 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, and save money immediately");} else {System. out. println ("Thread" + B + "Start, enter the bank, no location, go to the queue and wait");} try {semaphore. acquire (); bank. save (10); System. out. println (B + "account balance:" + bank. getAccount (); Thread. sleep (1, 1000); System. out. println ("Thread" + B + "save money, leave the Bank"); semaphore. release ();} catch (InterruptedException e) {e. printStackTrace () ;}}/ *** creates a thread and calls an internal class to start saving money */public void useThread () {Bank bank Bank = new Bank (); // define 10 new Semaphore semaphore = new Semaphore (2); // create a cache thread pool ExecutorService es = Executors. newCachedThreadPool (); // create 20 threads for (int I = 0; I <10; I ++) {// execute a thread es. submit (new Thread (new NewThread (bank, semaphore);} // close the Thread pool es. shutdown (); // get two licenses from the semaphore and keep the thread blocking semaphore until the license is obtained. acquireUninterruptibly (2); System. out. println ("to the point, the staff is going to eat"); // release the two licenses and return them to semaphore. release (2);} public static void main (String [] args) {SemaphoreThread test = new SemaphoreThread (); test. useThread ();}}


Interview Questions:
In many cases, multiple threads may need to access a small number of resources. Assume that several threads are running on the server to answer client requests. These threads need to connect to the same database, but at any time
Only a certain number of database connections can be obtained. How can you effectively allocate these fixed numbers of database connections to a large number of threads?

A:1.MethodApply synchronization lockEnsure that only one person can call this method at the same time. All other threads are waiting in queue, but in this case, even if there are 10 database connections, only one is in

Usage Status. In this way, system resources will be greatly wasted and the operating efficiency of the system will be very low.


2.Another method, of course, is to useSemaphoresBy using semaphores to permit the same number of available connections to the database, the efficiency and performance will be greatly improved.


How to use a java program to write semaphores (semaphore), if our teacher wants to manage the queue by himself

Oh... I'm going ~~

What is the Semaphore class of the Java concurrent library? How to use it? What is used?

Semaphore is a Java implementation of semaphores in multiple processes and multithreading. semaphores are used to achieve mutually exclusive access to resources. Of course, there are other implementation methods-management process, message transmission, and so on. We recommend that you first learn about how semaphores implement concurrency. After all, semaphores are a very difficult concurrency implementation mechanism.
 

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.