Junit测试多线程时的处理
之前在测试多线程发送邮件时,使用junit发现,junit在调用待测试的类的方法创建子线程处理任务,在主线程跳出该类方法回到junit test方法时,jvm被终止,所有还在处理任务的子线程都被关闭。
此时,可以用调用CountDownLatch类来进行子线程计数,子线程运行完时调用countDown()使计数减1,在主线程调用await()阻塞等待子线程全部处理完再返回junit test
代码如下:
/**
*
* @Title: sendTest
* @Desc: junit测试 多线程发送多封邮件
*
*/
@Test
public void sendTest() {
MyMail mm = new MyMail();
List<MailParam> mails = new ArrayList<>();
for (int i = 20; i > 0; i--) {
MailParam mail = new MailParam();
mail.setHost("smtp.163.com");
mail.setPort(25);
mail.setUser("xxx.com");
mail.setPassword("*****");
mail.setFrom("xxx@163.com");
mail.setTo(TO);
mail.setAgreement("smtp");
mail.setSSL(false);
mail.setSubject("呵呵");
mail.setContant("23333333333333333");
mails.add(mail);
}
mm.doWorks(mails, SEND);
}
/**
*
* @Title: doWork
* @Desc: 邮件工作开始,批量,多线程
*
* @param mail
* @param type
* 0:发送邮件 ; 1:接收邮件
*
*/
public void doWorks(List<MailParam> mails, int type) {
CountDownLatch count = new CountDownLatch(mails.size());//设置子线程数目
for (MailParam mail : mails) {
new Thread(new MailThread(mail, type, count)).start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
count.await();//等待子线程全部运行完
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* @Title: MailThread.java
* @desc: 邮件线程类
* @author mengchuan.li
*/
class MailThread implements Runnable {
private MailParam mail;
private int type;
private CountDownLatch count;
public MailThread(MailParam mail, int type, CountDownLatch count) {
this.mail = mail;
this.type = type;
this.count = count;
}
@Override
public void run() {
new MyMail().doWork(mail, type);
if (count != null) {
count.countDown();//计数减1
}
}
}