package com.jxh.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class TestSemaphore {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(5);
for(int i=0; i<20; i++) {
final int index = i;
Runnable runable = new Runnable() {
public void run() {
try {
semp.acquire();
System.out.println("Accessing " + index);
Thread.sleep(1000l);
semp.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executor.execute(runable);
}
executor.shutdown();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class TestSemaphore {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(5);
for(int i=0; i<20; i++) {
final int index = i;
Runnable runable = new Runnable() {
public void run() {
try {
semp.acquire();
System.out.println("Accessing " + index);
Thread.sleep(1000l);
semp.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executor.execute(runable);
}
executor.shutdown();
}
}