多线程测试工具(GroboUtils)的使用

本文介绍了一种利用Java库groboutils进行多线程并发测试的方法,并提供了具体的代码示例,展示了如何通过自定义多线程测试来验证系统的并发处理能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Maven依赖方式:

<dependency> 
      <groupId>net.sourceforge.groboutils</groupId> 
      <artifactId>groboutils-core</artifactId> 
      <version>5</version> 
    </dependency> 

注:需要第三方库支持:

RepositoryOpensymphony Releases
Repository urlhttps://oss.sonatype.org/content/repositories/opensymphony-releases


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.junit.Before;
import org.junit.Test;

import net.sourceforge.groboutils.junit.v1.MultiThreadedTestRunner;
import net.sourceforge.groboutils.junit.v1.TestRunnable;

/**
 * 
 * @Package testController
 * @Description: 多线程并发测试
 * @author 刘伟 15818570028@163.com
 * @date 2017年4月12日 上午10:28:20
 * @version V1.0
 */

public class TestMultiThread {
	int count = 0;// 并发测试count++

	@Before
	public void setup() {
	}

	/**
	 * 
	 * @Title: MultiRequestsTest
	 * @Description: 使用groboutils并发测试
	 * @throws InterruptedException
	 */
	@Test
	public void MultiRequestsTest() throws InterruptedException {
		// 构造一个Runner
		TestRunnable runner = new TestRunnable() {
			@Override
			public void runTest() throws Throwable {
				// 测试内容
				for (int i = 0; i < 10000; i++) {
					count++;
				}

			}
		};
		int runnerCount = 2;
		// Rnner数组,想当于并发多少个。
		TestRunnable[] trs = new TestRunnable[runnerCount];
		for (int i = 0; i < runnerCount; i++) {
			trs[i] = runner;
		}
		// 用于执行多线程测试用例的Runner,将前面定义的单个Runner组成的数组传入
		MultiThreadedTestRunner mttr = new MultiThreadedTestRunner(trs);
		try {
			// 开发并发执行数组里定义的内容
			mttr.runTestRunnables();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		TimeUnit.SECONDS.sleep(1);
		System.out.println(count);
	}

	@Test
	public void test() throws InterruptedException {
		Runnable run = () -> {
			for (int i = 0; i < 10000; i++) {
				count++;
			}
		};
		multithreads(run, 2);
		TimeUnit.SECONDS.sleep(1);
		System.out.println(count);
	}

	/**
	 * 
	 * @Title: multithreads
	 * @Description: 自己实现的多线程测试
	 * @param run
	 * @param thread
	 */
	public void multithreads(Runnable run, int thread) {
		CountDownLatch countDown = new CountDownLatch(thread);
		for (int i = 0; i < thread; i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						run.run();
					} finally {
						countDown.countDown();
					}
				}
			}).start();
		}

		try {
			countDown.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

参考资料:

Junit spring 多线程测试

转载于:https://my.oschina.net/u/1266221/blog/740256

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值