making program to send mail by different threads at the same time through parallel processing

丶灬走出姿态 提交于 2019-12-31 03:45:09

问题


I have the below program which send the mail using java mail api , now this the is the simple program i have developed now i want to modify in terms of parallel execution by using executorframework that i want that 5 different threads independently should trigger my this program but those 5 different threads should trigger simultaneously at the same time

lets say there are five different threads t1,t2,t3,t4 and t5 then all of them should independently hit my function which is main(@) is calling rite now but at the same time

below is my java code

public class SSendEmail {

    public static void main(String [] args) throws Exception, IOException, Exception{

        String smtpHost = "xxx";
        String mailSmtpPort = "000";
        String mailTo[] = {"sart@wer.com" };
        String mailCc[] = {"sart@wer.com" };






        xxsendmail(mailTo, mailCc, "sendername",
                "testsubject.", "testsubject..", smtpHost , mailSmtpPort);


    }  

回答1:


I think you would use a ScheduledExecutorService and call it like this.

ScheduledExecutorService exec = Executors.newScheduledThreadPool(amount);
for (int i = 0; i < amount; i++) {
    exec.schedule(yourMailSendingRunnable, delay, TimeUnit.MILLISECONDS);
}

You should replace amount, yourMailSendingRunnable and delay to account for your needs.




回答2:


As long your only requirement is that 5 threads should work concurrent, you are done with something like this:

public class SSendEmail implements Runnable {

   public static void main(String [] args) throws Exception, IOException, Exception{

      for(int i=0;i<5;i++) {
          new Thread(new SSendMail()).start();
      }
   }

   public void run() {

    String smtpHost = "xxx";
    String mailSmtpPort = "000";
    String mailTo[] = {"sart@wer.com" };
    String mailCc[] = {"sart@wer.com" };

    xxsendmail(mailTo, mailCc, "sendername",
            "testsubject.", "testsubject..", smtpHost , mailSmtpPort);
  }  
}

You will use an ExecutorService when more control is needed. E.g. ThreadPooleExecutor to limit the number of concurrent running threads when you have continues new threads, but you want limit to, say, 10 threads running at the same time.



来源:https://stackoverflow.com/questions/36504199/making-program-to-send-mail-by-different-threads-at-the-same-time-through-parall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!