java 并发测试_Java高并发测试代码

1、并发程序

/**

* 高并发测试:

* 创建threadNum个线程;

* 执行任务task

* @param threadNum 线程数量

* @param task 任务

*/

public static void parallelTesk(int threadNum, Runnable task){

// 1. 定义闭锁来拦截线程

final CountDownLatch startGate = new CountDownLatch(1);

final CountDownLatch endGate = new CountDownLatch(threadNum);

// 2. 创建指定数量的线程

for (int i = 0; i

Thread t = new Thread(() -> {

try {

startGate.await();

try {

task.run();

} finally {

endGate.countDown();

}

} catch (InterruptedException e) {

}

});

t.start();

}

// 3. 线程统一放行,并记录时间!

long start = System.nanoTime();

startGate.countDown();

try {

endGate.await();

} catch (InterruptedException e) {

}

long end = System.nanoTime();

System.out.println("cost times :" +(end - start));

}

2、应用

import java.util.concurrent.CountDownLatch;

public class Main {

/**

* 定义一个不安全方法:在高并发情况下得不到想要的结果

* queryTimes 是一个不安全的属性;

* getTimes是一个不安全方法;

*/

static int queryTimes = 0;

public static int getTimes(){

queryTimes = queryTimes +1;

return queryTimes;

}

/**

* 200个线程来执行获取getTimes

* @param args

*/

public static void main(String[] args) {

parallelTesk(200, new Runnable() {

@Override

public void run() {

System.out.println(getTimes());

}

});

}

/**

* 高并发测试:

* 创建threadNum个线程;

* 执行任务task

* @param threadNum 线程数量

* @param task 任务

*/

public static void parallelTesk(int threadNum, Runnable task){

// 1. 定义闭锁来拦截线程

final CountDownLatch startGate = new CountDownLatch(1);

final CountDownLatch endGate = new CountDownLatch(threadNum);

// 2. 创建指定数量的线程

for (int i = 0; i

Thread t = new Thread(() -> {

try {

startGate.await();

try {

task.run();

} finally {

endGate.countDown();

}

} catch (InterruptedException e) {

}

});

t.start();

}

// 3. 线程统一放行,并记录时间!

long start = System.nanoTime();

startGate.countDown();

try {

endGate.await();

} catch (InterruptedException e) {

}

long end = System.nanoTime();

System.out.println("cost times :" +(end - start));

}

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值