12345678910111213141516171819202122232425 |
- import java.util.concurrent.*;
- public class TestSemaphore {
- public static void main(String[] args) {
- int resources = 2;
- Semaphore semaphore = new Semaphore(resources);
- ExecutorService executor = Executors.newCachedThreadPool();
- for (int i = 1; i <= 10; i++) {
- final int num = i;
- executor.execute(() -> {
- try {
- semaphore.acquire();
- System.out.println("Thread " + num + " start.");
- Thread.sleep(100);
- System.out.println("Thread " + num + " end.");
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- semaphore.release();
- }
- });
- }
- executor.shutdown();
- }
- }
|