信号量-控制并发数量

 Semaphore 信号量,控制并发的数量即 控制同时有几个线程同时执行 。

线程在执行前调用Semaphore 的acquire()方法获取线程执行权限,如果信号量里面有余的令牌,则当前线程可以执行,没有的话就等待

线程执行结束则调用release(),释放当前的令牌,其他线程就可以获取这个令牌,继续执行

获取可以的剩余信号令牌:availablePermits() 

直接例子吧:

/**
 * 作用:Semaphore 信号量,控制并发的数量即 控制同时有几个线程同时执行
 * 场景:前提:一个商店的工人倒班工作,按照工时给工资
 *      商店同时需要5个人同时工作, 多余的其他工人等到这5个工人需要休息了,就顶上继续工作
 */
public class SemaphoreTest {

	public static void main(String[] args) {
		 Semaphore semaphore = new Semaphore(5); 
		 ExecutorService executor = Executors.newFixedThreadPool(30) ; 
		 
		 for(int i=0;i<10;i++ ){
			 executor.execute(  new SlaveThread4(semaphore,  i));	 
		 }
		 
		 executor.shutdown(); 
	}
}

//工人类
class SlaveThread4  implements Runnable {
	//工人编号
	private Integer number ; 
	//线程开始标识
	private Semaphore semaphore;
 
	
	public SlaveThread4(Semaphore semaphore ,  int number){
		this.number = number ;
		this.semaphore = semaphore ; 
	}
	
	@Override
	public void run() {
		
		try {
			semaphore.acquire(); 
			System.out.println( "工人  "+number+"  开始工作"+new Date());
			work() ; 
			semaphore.release();
			System.out.println( "工人  "+number+"  结束工作  ,  剩余空缺人:"+semaphore.availablePermits());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} 
		
	}
	
	//抬起
	public void work(){
		try {
			//抬起箱子总共花费时间 3s
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

猜你喜欢

转载自username2.iteye.com/blog/2243245