36套java进阶高级架构师视频+38套大数据视频 保证全是硬货需要的
+微信:
du13797566440
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;
/**java Semaphore限流
*/
public class worker {
public static void main(String[] args) {
final Semaphore semaphore = new Semaphore(5);//一次最多执行5个线程
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i < 20; i++) {
final int index=i;
newCachedThreadPool.execute(new Runnable() {
public void run() {
try {
semaphore.acquire();//获取许可证 ,
Thread.sleep(1000);
System.out.println(index);
semaphore.release(); //acquire和release之间只能有5个线程
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}