/**
*
* @author beiyaoyao
*/
public class SemaphoreDemo implements Runnable {
//設置有幾個線程可以進入執行的代碼段
final Semaphore semaphore = new Semaphore(5);
@Override
public void run() {
try {
semaphore.acquire();
Thread.sleep(5000);
System.out.println(Thread.currentThread().getId() + "exec");
//釋放信號量,如果不釋放導致內存泄漏,那麼進入該臨界區的線程資源就越來越少
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//newFixedThreadPool(10)用工廠生產一個容納10個線程的線程池
ExecutorService exec = Executors.newFixedThreadPool(10);
final SemaphoreDemo demo = new SemaphoreDemo();
for(int i = 0 ; i < 10 ; i ++){
exec.submit(demo);
}
exec.shutdown();
}
}
執行完該程序後,首先休眠5秒,結束後會輸出5個線程的ID,再休眠5秒,繼續輸出5個線程的id。輸出的線程id,以5個一組爲單位。