浏览 2585 次
锁定老帖子 主题:java并发测试用例模板
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-10-10
public class Test { public static void main(String[] args) { int count = 1000; ExecutorService executorService = Executors.newFixedThreadPool(count); for (int i = 0; i < count; i++) executorService.execute(new Test().new Task()); executorService.shutdown(); while (!executorService.isTerminated()) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Task implements Runnable { @Override public void run() { try { // 测试内容 } catch (Exception e) { e.printStackTrace(); } } } }如果要实现真正的并发同时执行,可通过CyclicBarrier来控制。 public class Test { public static void main(String[] args) { int count = 1000; CyclicBarrier cyclicBarrier = new CyclicBarrier(count); ExecutorService executorService = Executors.newFixedThreadPool(count); for (int i = 0; i < count; i++) executorService.execute(new Test().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(); // 测试内容 } catch (Exception e) { e.printStackTrace(); } } } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |