import java.util.concurrent.Semaphore;
public class SemaphoreTest {
public static Semaphore semaphore = new Semaphore(10);//创建信号量,每次限定10个信号同时访问
public static void main(String[] args){
for (int i=0;i<100;i++){
new Thread(new testRun()).start();//调用时只有10个线程同时进行,另外的线程处于等待状态
}
}
private static class testRun implements Runnable{
@Override
public void run() {
try {
semaphore.acquire();//使用一个信号
for (int i=0;i<1;i++){
System.out.println(Thread.currentThread().getName());
}
Thread.sleep(10000);
semaphore.release();//释放一个信号
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
参考:https://blog.csdn.net/zbc1090549839/article/details/53389602#commentBox