semaphore是java里边的信号灯,感觉很像blockqueue,嗯

 

package com.mutiple;

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 i = 0; i < 20; i++) {
			final int no = i;
			Runnable run = new Runnable() {
				
				@Override
				public void run() {
					try {
						semp.acquire();
						System.out.println("Accessing: "+no);
						long time = (long) (Math.random()*10000);
						System.out.println(time);
						Thread.sleep(time);
						semp.release();
						System.out.println("---------------"+semp.availablePermits());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
			exec.execute(run);
		}
		
		exec.shutdown();
	}

}