问题:测试类中测试调用多线程的接口时发现程序总是会自动结束,根本不管我的子线程状态的那种啊喂,查阅资料发现可能是测试类的机制不支持对多线程的测试:
初始代码如下(为了确保准确,这里加入了sleep):
@Test
public void test2() {
System.out.println("Start......test.........");
FundThread tFundThread = new FundThread();
tTestFundThread.start();
System.out.println("End.......test......");
}
public class TestFundThread extends Thread {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Start..........Thread.........");
}
}
执行结果发现控制台仅输出了:
Start..........test........
End..........test......
解决:
方法一:在主线程end之前加上Thread.sleep(),使主线程休眠一段时间,这个方法不推荐,主要是--1.时间到了如果子线程还没结束,程序依然会结束,--2.时间没到,但子线程很快结束了,依旧会等待,影响效率
方法二:使用CountDownLatch类的await(),countDown()方法,这里选用重写的
await(10000,TimeUnit.MILLISECONDS);区别再去await()方法会一直阻塞到子线程执行完,带参方法会在子线程执行完或到时间后强制中断,
所以改造后的代码如下:
@Test
public void test2() {
System.out.println("Start..........test........");
CountDownLatch tCountDownLatch = new CountDownLatch(1);
TestFundThread tTestFundThread = new TestFundThread(tCountDownLatch);
tTestFundThread.start();
try {
//Thread.sleep(1200);
tCountDownLatch.await(10000,TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("End..........test......");
}
public class TestFundThread extends Thread {
CountDownLatch tCountDownLatch = new CountDownLatch(1);
public TestFundThread(CountDownLatch tCountDownLatch) {
this.tCountDownLatch = tCountDownLatch;
}
@Override
public void run() {
System.out.println("Start..........Thread.........");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End..........Thread.........");
tCountDownLatch.countDown();
}
}
|