Java并发测试简单工具类

1,574 阅读1分钟

本工具类很简单,可以用于测试多线程下临界资源是否安全,以及测试数据库连接数等,有参考意义


	//总线程数
	private static int clientTotal = 1200;
	//并发数
    private static int threadTotal = 200;


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();
					//todo 用于测试的代码
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception:", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
    }