1. 程式人生 > >【java】java執行緒併發測試模版

【java】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