What are the more important methods in the Semaphore class
What are the more important methods in the Semaphore class, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
Semaphore is translated into semaphores literally, and Semaphore can control the number of threads accessed at the same time.
Acquire () gets a license, if not, waits, while release () releases a license. Some of the more important methods in the Semaphore class:
Public void acquire (): used to obtain a license, and if no license can be obtained, it will wait until it is granted.
Public void acquire (int permits): get permits licenses
Public void release () {}: release the license. Note that permission must be obtained before a license can be released.
Public void release (int permits) {}: the above four methods will be blocked by releasing permits licenses. If you want to get the execution result immediately, you can use the following methods
Public boolean tryAcquire (): attempts to obtain a license. If it succeeds, it immediately returns true. If it fails, it immediately returns false.
Public boolean tryAcquire (long timeout, TimeUnit unit): attempts to obtain a license. If the license is successful within the specified time, true is returned immediately, otherwise false is returned immediately.
Public boolean tryAcquire (int permits): try to get permits licenses. If the license is successful, return true immediately. If it fails, return false immediately.
Public boolean tryAcquire (int permits, long timeout, TimeUnit unit): attempts to obtain permits licenses. If the license is successful within the specified time, true is returned immediately. Otherwise, false is returned immediately.
You can also get the number of licenses available through the availablePermits () method.
`
Import java.util.concurrent.Semaphore;public class SemaphoreDemo {public static int num= 8 static class Worker extends Thread {private int num; private Semaphore semaphore; public Worker (int num,Semaphore semaphore) {this.num=num; this.semaphore = semaphore;} [@ Override] (https://my.oschina.net/u/1162528) public void run () {try {semaphore.acquire () System.out.println ("worker" + this.num+ "occupies a machine in production"); Thread.sleep (2000); System.out.println ("worker" + this.num+ "releases the machine"); semaphore.release ();} catch (InterruptedException e) {e.printStackTrace () } public static void main (String [] args) {Semaphore semaphore = new Semaphore (5); for (int I = 1; I