semphore线程执行的排队

package endual;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * semaphore可以维护当前访问自身的线程个数,并提供了同步机制。使用semaphore可以控制同时访问
 * 资源的线程个数,例如,实现一个文件运行的并发访问数。
 *    semaphore实现的功能类似于厕所有五个坑,那么假如有10个人来上厕所,那么同时能去上的值能是5
 *    个,其余的5个还是要等的,如果另外5个人中又有一个可以占用了,那么就可以上去了
 *    另外等待的5个人中可以是随机获得优先机会,也可以是按照先来后到得的顺序获取机会的,这取决于与构造
 *    semaphore对象传入的参数选项
 * @author endual
 *
 */
public class SemaphoreApp {

	public static void main(String[] args) {
		
		final ExecutorService es = Executors.newCachedThreadPool() ; //自动的开启线程
		final Semaphore sp = new Semaphore(3) ;
		
		for (int i=0; i < 10; i++) {
			System.out.println("---******----");
			Runnable command = new Runnable() {

				public void run() {

					try {
						sp.acquire() ;
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					System.out.println();
					System.out.println("----------进入--------------------------");
					System.out.println(Thread.currentThread().getName() );
					System.out.println( "剩余下有用的坑的个数是: " + (sp.availablePermits()));
					try {
						Thread.sleep(10000) ;
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					System.out.println("_____________离开_________________________");
					System.out.println();
					sp.release() ;
					System.out.println("已经离开了信号灯,当前可以用的坑的个数有 :" + (sp.availablePermits()));
				
				} //end run
				
			}; //end new
			es.execute(command) ; //执行线程
		} //end for 
		
		
	} //end main
} //end class 

 

 

 

  这个的话,结合线程池的使用就可以了。在同一时间,指定并发执行的线程的个数的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值