Postman
Apache Bench
Jmeter
代码实现:CountDownLatch、Semaphore
CountDownLatch
public class CountDownLatchTest {
private static final CountDownLatch cdl = new CountDownLatch(3);
public static void main(String[] args) throws InterruptedException {
System.out.println("开始");
new Thread(() -> {
try {
System.out.format("当前计数=%s,需等待 \n", cdl.getCount());
Thread.sleep(1000);
cdl.countDown();
System.out.format("当前计数=%s,需等待 \n", cdl.getCount());
Thread.sleep(1000);
cdl.countDown();
System.out.format("当前计数=%s,需等待 \n", cdl.getCount());
Thread.sleep(1000);
cdl.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}).start();
cdl.await(6000, TimeUnit.MILLISECONDS);
print();
System.out.println("结束");
}
private static void print() {
System.out.println("执行了");
}
}
Semaphore
public class SemaphoreTest {
private final static Semaphore semaphore = new Semaphore(5);
private final static int A_NUMS = 5;
private final static int B_NUMS = 5;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
IntStream.range(0,A_NUMS).forEach(x->{
try {
System.out.format("当前汽车准乘人数=%s \n", semaphore.availablePermits());
semaphore.acquireUninterruptibly();
System.out.println("A旅行团上车1人 \n");
Thread.sleep(new Random().nextInt(3000));
System.out.format("剩余汽车准乘人数=%s \n", semaphore.availablePermits());
}catch (Exception e){
e.printStackTrace();
}
});
}).start();
new Thread(() -> {
IntStream.range(0,B_NUMS).forEach(x->{
try {
System.out.format("当前汽车准乘人数=%s \n", semaphore.availablePermits());
semaphore.acquireUninterruptibly();
System.out.println("B旅行团上车1人 \n");
Thread.sleep(new Random().nextInt(3000));
System.out.format("剩余汽车准乘人数=%s \n", semaphore.availablePermits());
}catch (Exception e){
e.printStackTrace();
}
});
}).start();
}
}