Semaphore维护了当前访问的个数,提供同步机制,控制同时访问的个数。在数据结构中链表可以保存“无限”的节点,用Semaphore可以实现有限大小的链表。另外重入锁ReentrantLock也可以实现该功能,但实现上要负责些,代码也要复杂些。
下面的Demo中申明了一个只有5个许可的Semaphore,而有20个线程要访问这个资源,通过acquire()和release()获取和释放访问许可。
package com.cisco.learning;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class TestSemaphore {
public static void main(String[] args) {
// 线程池
ExecutorService exec = Executors.newCachedThreadPool();
// 只能个线程同时访问
final Semaphore semp = new Semaphore(5);
// 模拟个客户端访问
for (int index = 1; index < 21; index++) {
final int NO = index;
Runnable run = new Runnable() {
public void run() {
try {
// 获取许可
semp.acquire();
System.out.println("Accessing: " + NO);
Thread.sleep((long) (Math.random() * 1000));
// 访问完后,释放
System.out.println("Release: " + NO);
semp.release();
} catch (InterruptedException e) {
}
}
};
exec.execute(run);
}
// 退出线程池
exec.shutdown();
}
}
Accessing: 1
Accessing: 3
Accessing: 2
Accessing: 4
Accessing: 5
Release: 5
Accessing: 6
Release: 1
Accessing: 7
Release: 4
Accessing: 9
Release: 3
Accessing: 8
Release: 9
Accessing: 10
Release: 6
Accessing: 11
Release: 7
Accessing: 12
Release: 12
Accessing: 13
Release: 13
Accessing: 14
Release: 2
Accessing: 15
Release: 10
Accessing: 16
Release: 15
Accessing: 17
Release: 8
Accessing: 18
Release: 18
Accessing: 19
Release: 17
Accessing: 20
Release: 16
Release: 11
Release: 14
Release: 19
Release: 20