[Java Concurrency concurrent simulation of four ways]

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_42322103/article/details/102736170

Concurrent simulation of four ways

A, Postman

Postman is a simulation tool http request shall
Here Insert Picture Description
first show you the most basic use postman
create a Springboot project, test code is as follows:

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~";
    }
}

Here Insert Picture Description
For ease of operation, will generally

http://127.0.0.1:8080 address + port number is frequently used, it may be provided to the environment

Click the settings icon in the top right corner
Here Insert Picture Description
to select global
Here Insert Picture Description
input information
Here Insert Picture Description
after further testing will be able to engage in such a short
Here Insert Picture Description
after know the basic use, we look at how to simulate concurrent test

Here Insert Picture Description
Here Insert Picture Description
Fill in basic information, create
Here Insert Picture Description
at this time will create Concurrency folder, we can just test the example demo into this folder

Here Insert Picture Description
Here Insert Picture Description
This time you can see in the Concurrency tested this interface
Here Insert Picture Description
selection concurrent test:
Here Insert Picture Description
This time we want a pop-up box
Here Insert Picture Description
click Run Concurrency

You can immediately feel the CPU in the "burning", because you want to record and print the log, display the words one by one to, in fact, a test of speed, print speed than you see in the log, green indicates normal

Here Insert Picture Description

二、Apache Bench(AB)

ApacheBench is the Apache server comes with a web stress testing tool, referred to as ab.

ab又是一个命令行工具,对发起负载的本机要求很低,根据ab命令可以创建很多的并发访问线程,模拟多个访问者同时对某一URL地址进行访问,因此可以用来测试目标服务器的负载压力。总的来说ab工具小巧简单,上手学习较快,可以提供需要的基本性能指标,但是没有图形化结果,不能监控。

使用的话,首先需要安装Apache服务器

网站:传送门 http://httpd.apache.org/download.cgi

因为我的操作系统是windows10, 这里选择File for Microsoft Windows

Linux下的安装是非常简单的,这里不再演示

Here Insert Picture Description
选择 ApacheHaus
Here Insert Picture Description
进入下载页面 选择适合自己电脑的版本
Here Insert Picture Description
文件解压到本地文件夹下,如果不是解压在c盘,需要设置参数,注意文件路径最好都是英文

关于需要设置参数,conf->httpd.conf 使用文本编辑器打开,

需要修改的有三个地方:
Here Insert Picture Description
Here Insert Picture Description
运行根目录,修改成自己解压到本地的路径
Here Insert Picture Description
监听端口,默认监听端口是80,如果已被使用会报错需要修改,如果80端口未被使用,可不修改;如果修改了监听端口,则需要把ServerName localhost也相应改成同样的端 口号
Here Insert Picture Description
Here Insert Picture Description
DocumentRoot 测试文件存放地,且该目录必须存在
Here Insert Picture Description
配置完成后,命令行cmd进入D:\softUtil\Apache24\bin目录下

httpd.exe  -k  install

Here Insert Picture Description
启动:

httpd.exe -k start

测试:

-n :请求数
-c: 并发数

Here Insert Picture Description

三、并发模拟工具JMeter

JMeter也是一款性能测试工具,是图形化的。

下载地址:传送门 http://jmeter.apache.org/

Here Insert Picture Description
需要Java8+的环境
Here Insert Picture Description
解压到你觉得合适的目录下(注意最好是英文路径)
进入它的bin目录下 启动jmeter.bat即可
Here Insert Picture Description
使用很简单,首先在测试计划部分新建一个线程组
Here Insert Picture Description
Here Insert Picture Description
Here Insert Picture Description
设置好基础信息后添加HTTP请求(基本信息设置好没有OK哈,直接添加HTTP请求)
Here Insert Picture Description
填写HTTP请求相关的内容
Here Insert Picture Description
之后还要添加监听器,这里选择是图形结果
Here Insert Picture Description
再添加一个查看结果树吧
Here Insert Picture Description
在运行之前打开log Viewer
Here Insert Picture Description
下面开始运行:
Here Insert Picture Description
执行成功,来感受一下结果:
Here Insert Picture Description
点进去
Here Insert Picture Description
查看结果树
Here Insert Picture Description

四、代码模拟

这里需要用到一个类,就是CountDownLatch。

CountDownLatch是一个计数器闭锁,通过它可以完成类似于阻塞当前线程的功能,即:一个线程或多个线程一直等待,直到其他线程执行的操作完成。

CountDownLatch用一个给定的计数器来初始化,该计数器的操作是原子操作,即同时只能有一个线程去操作该计数器。调用该类await方法的线程会一直处于阻塞状态,直到其他线程调用countDown方法使当前计数器的值变为零,每次调用countDown计数器的值减1。当计数器值减至零时,所有因调用await()方法而处于等待状态的线程就会继续往下执行。这种现象只会出现一次,因为计数器不能被重置。

下图和它的方法可以体现出来:
Here Insert Picture Description
CountDownLatch类只提供了一个构造器:

public CountDownLatch(int count) {  };  //参数count为计数值

然后下面这3个方法是CountDownLatch类中最重要的方法(上图能够反映出来)

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

下面还需要看一个类Semaphore

Semaphore with CountDownLatch similar difference is that the value is acquired Semaphore is released, not as in the end as has been CountDownLatch Save.

It is also used to limit flow more similar function of the valve. If certain limited resources up to N threads can access, then more than N primary thread is not allowed to have access, at the same time when the end of the existing threads, will be released, and then allowed to come in the new thread. Somewhat similar to lock and unlock the lock process. Relatively speaking, he also has two major ways:

Obtaining permission to acquire (), the underlying implementation CountDownLatch.countdown () Similar;
for releasing authority release (), the underlying implementation acquire () is a reciprocal process.

Can be simulated concurrently by two classes:

have a test:

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++;
    }
}

Because the count is not thread safe, and not for protective measures, the result is wrong
Here Insert Picture Description

The above is a simple form of concurrent simulation code, it is worth noting that two classes are not designed to do concurrent simulation, they are so widely mentioned here, such as after updating Java network programming something, will be described in detail they.

Guess you like

Origin blog.csdn.net/qq_42322103/article/details/102736170