原创转载请注明出处:http://agilestyle.iteye.com/blog/2343040
availablePermits()返回此Semaphore对象中当前可用的permits个数
drainPermits()获取并返回立即可用的所有permits个数,并将可用permits置为0
AvailablePermitsTest.java
package org.fool.java.concurrent.semaphore.availabledrainpermits;
import java.util.concurrent.Semaphore;
public class AvailablePermitsTest {
public static void main(String[] args) {
MyService service = new MyService();
service.testMethod();
}
public static class MyService {
private Semaphore semaphore = new Semaphore(10);
public void testMethod() {
try {
semaphore.acquire();
System.out.println(semaphore.availablePermits()); // outputs 9
System.out.println(semaphore.availablePermits()); // outputs 9
System.out.println(semaphore.availablePermits()); // outputs 9
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
}
Run
DrainPermitsTest.java
package org.fool.java.concurrent.semaphore.availabledrainpermits;
import java.util.concurrent.Semaphore;
public class DrainPermitsTest {
public static void main(String[] args) {
MyService service = new MyService();
service.testMethod();
}
public static class MyService {
private Semaphore semaphore = new Semaphore(10);
public void testMethod() {
try {
semaphore.acquire();
System.out.println(semaphore.availablePermits());
System.out.println(semaphore.drainPermits() + " " + semaphore.availablePermits());
System.out.println(semaphore.drainPermits() + " " + semaphore.availablePermits());
System.out.println(semaphore.drainPermits() + " " + semaphore.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
}
Run