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
这个的话,结合线程池的使用就可以了。在同一时间,指定并发执行的线程的个数的。