- * 目的:了解信号灯
- *x信号灯的作用:
- * 控制一次运行线程的数量
- */
- public class SemaphoreTest {
- public static void main(String[] args) {
-
- ExecutorService threadPool = Executors.newCachedThreadPool();
- final Semaphore semaphore = new Semaphore(3); //定义一个有三个信号的Semaphore
-
- for(int i=0;i<7;i++){
- Runnable runnable = new Runnable(){
- public void run() {
- try {
- semaphore.acquire(); //每获取一次信号灯,信号灯的数量就减一。
- //如果没有了信号灯,线程等待其他线程释放信号灯
- //Thread.sleep(2000);
- System.out.println(Thread.currentThread().getName()+":正在运行,"+
- "目前可利用的信号灯为:"+semaphore.availablePermits());
- Thread.sleep(4000);
- System.out.println(Thread.currentThread().getName()+":即将离开");
- }catch (InterruptedException e) {
- e.printStackTrace();
- }finally{
- semaphore.release(); //释放信号灯,信号灯的数量加一
- }
- }
- };
- threadPool.execute(runnable);
- }
- threadPool.shutdown();
- }
- }
复制代码 |
|