java并发测试用例模板

这里申请了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();  
               }  
          }  
     }  
}  

转http://flysnowxf.iteye.com/blog/1188496

你可能感兴趣的:(java并发测试用例模板)