java代码中使用多线程并行

@ResponseBody
@RequestMapping("/test")
public String testThread(){
Date date1 = new Date();
System.out.println("注册用户");
// sendEmail();
// sendMsg();
Thread thread = new Thread(() -> sendEmail());
Thread thread2 = new Thread(() -> sendMsg());
thread.start();
thread2.start();
try {
thread.join();
thread2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Date date2 = new Date();
System.out.println("注册用户总共耗时:"+(date2.getTime()-date1.getTime()));
return "success";
}

private void sendEmail(){
System.out.println("发送邮件开始...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("发送邮件结束...");
}

private void sendMsg(){
System.out.println("发送短信开始...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("发送短信结束...");
}

猜你喜欢

转载自blog.csdn.net/qq_42461674/article/details/80951445