论坛首页 Java企业应用论坛

java并发测试用例模板

浏览 2585 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-10-10  
这里申请了1000个线程,并且执行1000次任务。当所有任务完成后,main退出。
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();
               }
          }
     }
}
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics