并发模拟的四种方式 + 工具,超级实用!
java1234
共 4329字,需浏览 9分钟
·
2022-01-06 18:37
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
并发模拟的四种方式
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("test")
public class TestConrtoller {
@GetMapping("demo")
public String testDemo() {
return "result~";
}
}
httpd.exe -k install
httpd.exe -k start
public CountDownLatch(int count) { }; //参数count为计数值
public void await() throws InterruptedException { }; //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { }; //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public void countDown() { }; //将count值减1
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*;
@Slf4j
public class CuncurrencyTest {
// 请求总数
public static int clientTotal = 5000;
// 同时并发执行的线程总数
public static int threadTotal = 200;
public static int count = 0;
public static void main(String[] args) throws InterruptedException {
// 定义线程池
ExecutorService executorService = Executors.newCachedThreadPool();
// 定义信号量 最大的线程数量
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
add();
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
log.error("exception",e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
log.info("count:{}",count);
}
private static void add() {
count++;
}
}
作者:沉晓
来源:csdn.net/qq_42322103/article/details/102736170
加锋哥微信: java1239 围观锋哥朋友圈,每天推送Java干货!
评论