Java thread pool Send mail __java

Source: Internet
Author: User
Tags sendmsg thread class

To get a sense of how the Java thread pool is used, just to make a simple email notification middle function, write down this note. Laughed


Servlet Code Sendemailservlet.java:

Package servlet;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.concurrent.BlockingQueue;
Import Java.util.concurrent.LinkedBlockingDeque;
Import Java.util.concurrent.ThreadPoolExecutor;

Import Java.util.concurrent.TimeUnit;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; /** * Send mail servlet * @author Gandalf * * */public class Sendemailservlet extends httpservlet{private static final in t corepoolsize = 1;
	
	The number of core threads saved in the thread pool. private static final int maximumpoolsize = 4;
	
	The maximum number of threads that the thread pool allows to create. Private static final Long KeepAliveTime = 0;
	
	The time at which redundant threads are terminated when the total number of threads in the thread pool is greater than the number of core threads.
	
	Message Queuing (thread sharing) private static blockingqueue<runnable> Emailqueue = new linkedblockingdeque<runnable> (); Instantiate thread pool (thread sharing) private static Threadpoolexecutor threadpool= new Threadpoolexecutor (Corepoolsize, Maximumpoolsize, KeepAliveTime, Timeunit.seconDS, Emailqueue,new Threadpoolexecutor.abortpolicy ()); @Override protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException
	{DoPost (req, resp); @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, Ioexcep
		
		tion {//content to be sent String content = Req.getparameter ("msg");
		
		Prints the current active thread and queue size System.out.println ("--current thread pool size" + threadpool.getpoolsize () + "", Current queue Size "+emailqueue.size () +" ");
	
		Join Queue Threadpool.execute (new Sendthread (content));
		Returns the result printwriter out = Resp.getwriter ();
	Out.println ("over");
		@Override public void Destroy () {//Close thread pool Threadpool.shutdown ();
	Super.destroy ();
 }
	

}



To process the thread class Sendthread.java for sending messages:


Package servlet;

/**
 * Send mail thread
 * @author Gandalf
 * */public
class Sendthread implements runnable{
	
	private String content;
	
	Public Sendthread (String content) {
		this.content = content;
	}
	
	@Override public
	Void Run () {
		
		try {
			//Send Message ....
			
			
			Thread.Sleep (1000);
			System.out.println ("SendMail:" +content);
		} catch (Interruptedexception e) {
			e.printstacktrace ();}}}



Web.xml configuration:

<servlet>
      <servlet-name>sendMsg</servlet-name>
      <servlet-class>servlet. sendemailservlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name >sendMsg</servlet-name>
      <url-pattern>/sendMsg.do</url-pattern>
  </ Servlet-mapping>


Test class to send a request to the 127.0.0.1/projectname/sendmsg.do by get way:

Package test;
Import Java.io.BufferedReader;
Import Java.io.InputStreamReader;
Import java.net.HttpURLConnection;

Import Java.net.URL; public class ThreadPoolTest1 {public static void main (string[] args) {for (int i=0; i<) {New i++ (i
			+ "-t1"). Run ();
			New Mythread (i+ "-t2"). Run ();
			New Mythread (i+ "-t3"). Run ();
	
		New Mythread (i+ "-t4"). Run ();
	
	Class Mythread implements runnable{private String name;
	Public Mythread (String name) {this.name = name;
			@Override public void Run () {try {thread.sleep (500);
			System.out.println (name+ "-----");
		    URL getUrl = new URL ("Http://127.0.0.1/ThreadPool/sendMsg.do?msg=sendemailNO:" +name);
	        HttpURLConnection connection = (httpurlconnection) getUrl. OpenConnection ();
	        To connect, but actually the GET request will be sent to the server Connection.connect () in the Connection.getinputstream () function in the next sentence. Gets the input stream and reads BufferedReader reader with reader = new BufferedReader (New INPUTSTREAMREader (Connection.getinputstream (), "Utf-8"))//Set encoding, otherwise Chinese garbled String lines;
	        while ((lines = Reader.readline ())!= null) {System.out.println (lines);
	        } reader.close ();
			
		Disconnect the connection connection.disconnect ();
		catch (Exception e) {e.printstacktrace ();
 }
	}
	
}


Test results:

--Current thread pool size "0", Current queue size "0"
--current thread pool size "1", Current queue size "0"
sendmail:sendemailno:0-t1
--Current thread pool size "1", Current queue size "0"
--Current thread pool size "1", Current queue Size "1"
sendmail:sendemailno:0-t2
--Current thread pool size "1", Current queue Size "1"-
-current thread pool size "1", Current queue Size "2" "
sendmail:sendemailno:0-t3
--Current thread pool size" 1 ", Current queue Size" 2 "
--current thread pool size" 1 ", Current queue Size" 3 "
SendMail: Sendemailno:0-t4
--Current thread pool size "1", Current queue Size "3"-
-current thread pool size "1", Current queue Size "4"
sendmail:sendemailno:1-t1
- -Current thread pool size "1", Current queue Size "4"
--current thread pool size "1", Current queue Size "5"
sendmail:sendemailno:1-t2
--Current thread pool size "1", Current queue Size "5"
--Current thread pool size "1", Current queue Size "6"
sendmail:sendemailno:1-t3
--Current thread pool size "1", Current queue Size "6"
--current thread pool size "1", Current Queue Size "7"
sendmail:sendemailno:1-t4
--Current thread pool size "1", Current queue Size "7"
--current thread pool size "1", Current queue Size "8"
SendMail : Sendemailno:2-t1
sendmail:sendemailno:2-t2
sendmail:sendemailno:2-t3


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.