java Semaphore 简单限流使用demo
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class ThreadTest1 {
private static Integer count = 300;
private static ExecutorService pool = Executors.newFixedThreadPool(count);
//信号量,控制流量;每次处理10个线程
private static Semaphore semaphore = new Semaphore(10);
//两个线程配对,交换exchange方法内的数据;
private static Exchanger<String> exchanger = new Exchanger();
public static void main(String[] args) {
for (int i = 0; i < count; i++) {
pool.execute(() -> {
try {
semaphore.acquire();
String x = exchanger.exchange("这是线程 - " + Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName() + ", " + x);
Thread.sleep(2000);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
pool.shutdown();
}
}