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