作者:月雨淅淅 | 来源:互联网 | 2023-09-24 09:49
线程基础知识复习
通过Callable和FutureTask创建线程,步骤如下:
- 创建Callable接口的实现类,并实现Call方法;
- 创建Callable实现类的实现,使用FutureTask类包装Callable对象,该FutureTask对象封装了Callable对象的Call方法的返回值;
- 使用FutureTask对象作为Thread对象的target创建并启动线程;
- 调用FutureTask对象的get()方法来获取子线程执行结束的返回值。
public class Demo{public static void main(String[] args){Callable call &#61; new MyCallable();FutureTask<Object> task &#61; new FutureTask<Object>(call);Thread t &#61; new Thread(task);t.start();try {System.out.println(task.get());} catch (Exception e) {e.printStackTrace();}}}class MyCallable implements Callable<Object>{&#64;Overridepublic Object call() throws Exception{System.out.println(Thread.currentThread().getName());return null;}}
通过线程池创建线程&#xff0c;如下&#xff1a;
public class ThreadDemo{public static void main(String[] args){FutureTask<Integer> futureTask &#61; new FutureTask<Integer>(new CallbleThread());ExecutorService executor &#61; Executors.newCachedThreadPool();executor.submit(futureTask);executor.shutdown();while(!futureTask.isDone()){System.out.println("子线程还没做完&#xff0c;我再睡会");TimeUnit.SECONDS.sleep(1);}try {System.out.println("子线程运行的结果&#xff1a;"&#43;futureTask.get());} catch (Exception e) {e.printStackTrace();}}
}
class CallbleThread implements Callable<Integer>{&#64;Overridepublic Integer call() throws Exception{System.out.println("线程池创建的线程&#xff1a;"&#43;Thread.currentThread().getName());TimeUnit.SECONDS.sleep(2);return 2;}
}
发送邮件
在独立线程中发送邮件&#xff1a;
public class SendMailUtil{private final Logger logger &#61; Logger.getLogger(this.class);public Boolean sendMailWithTask(Mailbox mailbox){ExecutorService exec &#61; executors.newCachedThreadPool();MailTask task &#61; new MailTask();task.mailbox &#61; mailbox;String failReason &#61; null;Future<Boolean> future &#61; exec.submit(task);Boolean taskResult &#61; false;try{taskResult &#61; future.get(120,TimeUnit.SECONDS);taskResult &#61; true;}catch(InterruptedException e){failReason &#61; "主线程在等待计算结果时被中断&#xff01;" &#43; e.getMessage();}catch(ExecutionException e){failReason &#61; "主线程等待计算结果&#xff0c;但计算抛出异常&#xff01;" &#43; e.getMessage();}catch(TimeoutException e){failReason &#61; "主线程等待计算结果超时&#xff0c;因此中断任务线程&#xff01;" &#43; e.getMessage();}finally{if(failReason!&#61;null){logger.info(failReason);}}return taskResult ;}class MailTask implements Callable<Boolean>{public Mailbox mailbox &#61; null;public Boolean call() throws Exception{result &#61; MailSender.send(mailbox);return result;}}
}
MailSender类
public class MailSender{public static boolean send(Mailbox mailbox) throws Exception {MyAuthenticator authenticator &#61; null;Properties pro &#61; mailbox.getProperties();if (mailbox.getValidate()) {String password &#61; mailbox.getPassword();authenticator &#61; new MyAuthenticator(mailbox.getEmail(),password );}Session sendMailSession &#61; Session.getInstance(pro, authenticator);Message mailMessage &#61; new MimeMessage(sendMailSession);Address from &#61; new InternetAddress(mailbox.getEmail());mailMessage.setFrom(from);Address to &#61; new InternetAddress(mailbox.getToAddress());mailMessage.setRecipient(Message.RecipientType.TO, to);mailMessage.setSubject(mailbox.getSubject());mailMessage.setSentDate(new Date());Multipart mainPart1 &#61; new MimeMultipart();BodyPart html &#61; new MimeBodyPart();html.setContent("hehehe","text/html; charset&#61;utf-8");mainPart1.addBodyPart(html);mailMessage.setContent(mainPart1);Transport.send(mailMessage);return true;}
}
MailBox类&#xff1a;
public class Mailbox {private Integer mailboxId;private String email;private String password;private String protocol;private String mailServerHost;private String mailServerPort;private String passwordEncrypt;private Boolean validate;private String toAddress;private String subject;private String connectType;&#64;JsonIgnorepublic Properties getProperties() {Properties p &#61; new Properties();p.put("mail."&#43;this.protocol&#43;".host", this.mailServerHost);p.put("mail."&#43;this.protocol&#43;".port", this.mailServerPort);p.put("mail."&#43;this.protocol&#43;".auth", validate);if("TLS".equals(this.connectType)){p.put("mail."&#43;this.protocol&#43;".starttls.enable", true);}else if("SSL".equals(this.connectType)){p.put("mail."&#43;this.protocol&#43;".ssl.enable", true);}return p;}
}