并发测试的Java实现

如果单纯的说并发测试,现在有很多现成的测试工具就可以做到,比如Jmeter,但是如果你有需要自己做一些简单的接口测试的话,可以用下面的代码。

要多个线程同时开始运行,一般有两种做法,一种是用CountDownLatch,一种则是CyclicBarrier,我这里是用CyclicBarrier来实现多个线程并发。
利用CyclicBarrier来进行完成多个多线程的并发的代理示例。
这里用的是runnable,没有返回值。

(1)没有返回值的的代码:

public void testCycleBarrier () {
	// 并发次数
 	int testCount = 100;
    CyclicBarrier cyclicBarrier = new CyclicBarrier(testCount);
    ArrayList<Future<String>> results = new ArrayList<>();
    ExecutorService executorService = Executors.newFixedThreadPool(testCount);
    for (int i = 0; i < testCount; i++) {
        executorService.execute(new Task(cyclicBarrier));
    }
    executorService.shutdown();
    while (!executorService.isTerminated()) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class Task implements Runnable {
    private CyclicBarrier cyclicBarrier;

    public Task(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            // 等待所有任务准备就绪
            cyclicBarrier.await();
            // 测试内容
            System.out.println("hello word");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

(2)有返回值的需求, 用Callable 这个接口来进行返回值:

public void testCycleBarrierWithCallable () {
	// 并发次数
    int testCount = 100;
    CyclicBarrier cyclicBarrier = new CyclicBarrier(testCount);
    ArrayList<Future<String>> results = new ArrayList<>();
    ExecutorService executorService = Executors.newFixedThreadPool(testCount);
     for (int i = 0; i < testCount; i++) {
         results.add(executorService.submit(new TaskFromCallable(cyclicBarrier)));
    }
    //        等待所有的线程的返回值都结束 
    boolean isDone = false;
    while (!isDone) {
        isDone = true;
        for (Future<String> future : results) {
            if (!future.isDone()) {
                isDone = false;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {

                }
                break;
            }
        }
    }
    executorService.shutdown();
    for (Future<String> future : results) {
        try {
        //  取返回值
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
public class TaskFromCallable implements Callable<String> {
    private CyclicBarrier cyclicBarrier;
    public TaskFromCallable(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public String call() throws Exception {
        return "hello ";
    }
}

以上两个就是根据并发测试的核心代码。

你可能感兴趣的:(编程日记,Java)