junit 不能用于测试多线程

线程类:

public class Thread1 implements Runnable {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for(int i=0;i<10000;i++){
            System.out.print(i+" ");
        }
    }
        
}

测试类:

public class MultiThreadTest {

    
    @Test
    public void test() throws IOException, InterruptedException{

        Runnable  Thread1 = new Thread1();

        new Thread(Thread1).start();
    //    Thread.sleep(10000);
        System.out.println(" main thread terminate");

    }
    
}

输出结果:

terminate
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
总结:

在线程类中,循环打印10000 个数字,但是在测试类中只打印了一部分.如果在测试类中把Thread.sleep() 的注释去掉,则可以打印全部的数字.
如果把代码放到正常的main() 中执行,也可以打印全部数字出来.

其实junit是将test作为参数传递给了TestRunner的main函数。并通过main函数进行执行。test函数在main中执行。如果test执行结束,那么main将会调用System.exit(0);
即使还有其他的线程在运行,main也会调用System.exit(0);
System.exit()是系统调用,通知系统立即结束jvm的运行,即使jvm中有线程在运行,jvm也会停止的。所以会出现之前的那种情况。其中System.exit(0);的参数如果是0,表示系统正常退出,如果是非0,表示系统异常退出。

junit TestRunner 部分源代码:

junit.textui.TestRunner
 public static void main (String[] args) {
      TestRunner aTestRunner = new TestRunner();
      try {
        TestResult r = aTestRunner.start(args);
       if (!(r.wasSuccessful()))
          System.exit (1);
       System.exit(0);
      } catch (Exception e) {
       System.err.println(e.getMessage());
        System.exit(2);
      }
   }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值