[置顶] Junit4多线程测试

在使用Junit4进行多线程测试的时候,大家一定要注意,当Junit方法的的执行线程执行完你的那段测试代码后会停止所有由你的测试代码启动的线程。举个例子,大家来看一下:
[java] view plaincopy
  1. @Test  
  2.     public void t() throws FileNotFoundException, InterruptedException, ExecutionException{  
  3.         //创建一个线程池      
  4.         ExecutorService pool = Executors.newFixedThreadPool(2);      
  5.         //创建两个有返回值的任务      
  6.         Callable c1 = new Callable<String>() {  
  7.             @Override  
  8.             public String call() throws Exception {  
  9.                 for(int i = 0 ; i < 100000; i++){System.out.println("1:"+i);};  
  10.                 return "1";  
  11.             }  
  12.         };  
  13.         Callable c2 = new Callable<String>() {  
  14.             @Override  
  15.             public String call() throws Exception {  
  16.                 for(int i = 0 ; i < 100000; i++){System.out.println("2:"+i);};  
  17.                 return "2";  
  18.             }  
  19.         };  
  20.         //执行任务并获取Future对象      
  21.         Future<String> f1 = pool.submit(c1);      
  22.         Future<String> f2 = pool.submit(c2);      
  23.         //从Future对象上获取任务的返回值,并输出到控制台      
  24.         System.out.println(">>>>>>>>>>>>>>>>>>>>>>"+f1.get());          
  25.         //关闭线程池      
  26.         System.out.println("************************************begin end");  
  27.         pool.shutdown();   
  28.         System.out.println("************************************end");  
  29.         while(!pool.isTerminated());  

你可能感兴趣的:([置顶] Junit4多线程测试)