并发模拟工具

  • Postman : HTTP请求模拟工具。
  • Apache Bench(AB):Apache附带的网站性能测试工具。
  • JMeter :Apache组织开发的压力测试工具。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java并发模拟工具类的介绍和示例: 1. CountDownLatch(线程计数器) CountDownLatch是一个同步辅助类,它允许一个或多个线程等待其他线程完成操作后再继续执行。它通过一个计数器来实现,计数器的初始值可以设置为线程的数量,每个线程完成任务时,计数器的值减1,当计数器的值为0时,等待的线程将被唤醒。 ```java import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { int threadCount = 5; CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { Thread thread = new Thread(new Worker(latch)); thread.start(); } latch.await(); // 等待所有线程完成任务 System.out.println("All threads have completed their tasks."); } static class Worker implements Runnable { private final CountDownLatch latch; public Worker(CountDownLatch latch) { this.latch = latch; } @Override public void run() { // 模拟线程执行任务 try { Thread.sleep(1000); System.out.println("Thread " + Thread.currentThread().getId() + " has completed its task."); } catch (InterruptedException e) { e.printStackTrace(); } latch.countDown(); // 完成任务后计数器减1 } } } ``` 2. CyclicBarrier(回环栅栏) CyclicBarrier是一个同步辅助类,它允许一组线程互相等待,直到所有线程都到达某个公共屏障点。当所有线程都到达屏障点后,屏障点上的任务将被执行。 ```java import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class CyclicBarrierDemo { public static void main(String[] args) { int threadCount = 3; CyclicBarrier barrier = new CyclicBarrier(threadCount, () -> { System.out.println("All threads have reached the barrier."); }); for (int i = 0; i < threadCount; i++) { Thread thread = new Thread(new Worker(barrier)); thread.start(); } } static class Worker implements Runnable { private final CyclicBarrier barrier; public Worker(CyclicBarrier barrier) { this.barrier = barrier; } @Override public void run() { // 模拟线程执行任务 try { Thread.sleep(1000); System.out.println("Thread " + Thread.currentThread().getId() + " has reached the barrier."); barrier.await(); // 等待其他线程到达屏障点 System.out.println("Thread " + Thread.currentThread().getId() + " continues to execute."); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值