並法包信號量的使用

https://www.cnblogs.com/amosli/p/3687776.html

 

/** 
* @ClassName: SemaPhoreTest
* @Description: 線程通信中的"信號燈"
* @author: amosli
* @email:[email protected]
* @date Apr 25, 2014 12:06:22 AM
*/
public class SemaPhoreTest {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newCachedThreadPool();

final Semaphore semaphore=new Semaphore(3);
for(int i=0;i<10;i++){
threadPool.execute(new Runnable() {
public void run() {
try {
semaphore.acquire();//獲取一個可用的permits
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("線程 " + Thread.currentThread().getName()+" 已進入. " + "目前已經有"+(3-semaphore.availablePermits())+" 個線程進入");
try {
Thread.sleep(new Random().nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("線程 "+Thread.currentThread().getName()+ " 即將離開...");
semaphore.release();//釋放一個線程
System.out.println("線程 "+Thread.currentThread().getName()+ " 已離開. 當前有"+(3-semaphore.availablePermits())+"併發");
}
});
}
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章