Multithreading is a compulsory course of getting started in Java, however, to contact with the EE, this homework will be returned to the teacher, at least I am such, hehe. But when used, I still can think about, plus degrees Niang help, can regain back, here I interrupt a small story, is my own personal experience, I hope to help my peers. Before the students, learning Java is not so hard, some things just may not tress, a lot of knowledge points in the brain a little impression is not very deep, I remember once I went to a company interview, the interviewer asked me, thread this piece, you know? As an interviewer, Who can say is not ripe, although I really do not know, but I answered on the spot is OK, and then fool, the interviewer asked, what is the use of the thread lock? But then I felt the problem was simple, so excited and tense that the brain pumped, and replied: "In order to ensure" linear "safe, then there is no then! ....... Well, I still think it's right, then I found out that I was wrong, eh ... Hope everyone warning, although as a programmer, without the concept of things, but in front of others, or can not be wrong shred make mistakes, after all come out to work, a lot of details will determine your future!
Good words not much, return to the point, today I would like to say is in the Web project, that is, in the Java EE application of multi-threaded services, I also in the project has to pay attention to this piece, beforehand did a lot of homework, after all, not used before, Deliberately write down and share your own practices and ideas. Here I say my project environment is SSH, and the other frameworks are similar.
Since it is multi-threading, it is the main actor thread class, the protagonist play
Package Com.smartsoft.thread;import Java.util.arraylist;import Java.util.list;import net.sf.json.jsonobject;import Org.apache.commons.httpclient.httpclient;import Org.apache.commons.httpclient.methods.postmethod;import Org.apache.commons.httpclient.methods.requestentity;import Org.apache.commons.httpclient.methods.stringrequestentity;import Org.apache.log4j.logger;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.web.context.support.springbeanautowiringsupport;import Com.google.gson.gson;import Com.smartsoft.common.constants;import Com.smartsoft.model.gameset;import Com.smartsoft.service.GamesetService; Import com.smartsoft.task.socketresultmodel;import com.smartsoft.util.systemconfig;/** * Main thread * * */public class Newgamesetthread extends Thread {private Logger Logger = Logger.getlogger (newgamesetthread.class);p rivate list< gameset> templist = new arraylist<gameset> ();p rivate Long sleeptime = 3 * 1000;private Gson Gson = new Gson ();p UB LiC Newgamesetthread () {springbeanautowiringsupport.processinjectionbasedoncurrentcontext (this);} @Autowiredprivate gamesetservice gamesetservice;public void Run () {//prevents multiple thread concurrently doing the operation of the repository, which consumes multiple try { Thread.CurrentThread (); Thread.Sleep (5 * 1000);} catch (Interruptedexception E1) {Logger.error (e1);} Logger.info ("Newgameset Thread is Started ... "); list<gameset> standbylist = new arraylist<gameset> ();//Loop Execution task while (true) {try {boolean bool = false;//Get message either Gettask (Standbylist), if (!standbylist.isempty ()) {//If there are data in the set of messages to be pushed (int i = 0; i < standbylist.size (); i++) {bool = false;try {Gameset task = Standbylist.get (i);//Push Reportbool = Httppush (Task);//Update messageupdatestatus (task, Boo l);} catch (Exception e) {logger.error (e.tostring (), e); continue;} finally {try {super.finalize ();} catch (Throwable e) {Logge R.error (E.tostring (), E);}}}} Standbylist.clear (); Thread.Sleep (sleeptime);} catch (Exception e) {logger.error (e.tostring (), e); continue;}}} private void UpdateStatus (GAmeset task, Boolean bool) {if (bool) {task.setpush_status ("1");} else {task.setpush_status ("0");} Gamesetservice.update (Task); Logger.info ("Newgameset Thread update Push Status ID:" + task.getid ());} Private Boolean Httppush (Gameset Task) {Pushmodel Pushmodel = new Pushmodel ("All", Task); String json = Gson.tojson (Pushmodel); Logger.info ("Newgameset Thread Push Message: \ n" + JSON); int result = Sendhttprequest Tosocketserverwithjson (JSON); Logger.info ("Newgameset Thread ID:" + task.getid () + "Push Result:" + (Result = = 1?) Success ":" Failure "); return result = = 1? True:false;} /** * httpClient * * @param reqstr * @param urlconfig * @param contentType * @return */private static int sendhttprequest (String reqstr, String urlconfig, String contentType) {try {Postmethod Postmethod = new Postmethod (urlconfig); Requestentity requestentity = new Stringrequestentity (Reqstr, ContentType, Constants.content_encoding_utf8); Postmethod.setrequestentity (requestentity); HttpClient HttpClient = new HtTpclient (); Httpclient.executemethod (Postmethod); Socketresultmodel Socketresult = (Socketresultmodel) Jsonobject.tobean (Jsonobject.fromobject ( Postmethod.getresponsebodyasstring ()), socketresultmodel.class); Integer httpstatus = Socketresult.getcode (); return Httpstatus = = 1? 1:0;} catch (Exception e) {e.printstacktrace (); return 0;}} private static int Sendhttprequesttosocketserverwithjson (string reqstr) {String url = systemconfig.get ("socket.host") + ":" + systemconfig.get ("Socket.port"); return sendhttprequest (Reqstr, URL, constants.http_content_type_application_ JSON);} /** * Get Message Task * * @param standbylist */private void Gettask (list<gameset> standbylist) {//Get high priority send task Templist = new Arraylist<gameset> (threadvariables.newgamesetlist); ThreadVariables.newGameSetList.removeAll (templist); Standbylist.addall (templist);//emptying Temporary list templist.clear ();} public static void Main (string[] args) {Gson Gson = new Gson (); Gameset task = new Gameset (); Task.setid (1L); Task.setgame_no (8); Pushmodel PusHmodel = new Pushmodel ("All", Task); String json = Gson.tojson (Pushmodel); SYSTEM.OUT.PRINTLN (JSON);}}
Requirements are not timed to push the message to another server, but the message is not sure when to come, how many, this thing is not good with the timer to achieve, can only use thread monitoring to run
The business logic is very simple, I will add the message to the collection somewhere else, and thread to constantly listen to the collection whether there is a message, there is immediately pushed out, no do not do anything
Package Com.smartsoft.thread;import Java.util.arraylist;import Java.util.collections;import java.util.List;import Com.smartsoft.model.gameset;public class Threadvariables {/** * callback task List */public static list<gameset> Newgamesetlist = collections.synchronizedlist (New arraylist<gameset> ());p ublic static void Addnewgamesetlist ( Gameset gameset) {newgamesetlist.add (Gameset);}}
This collection of course is to bring the thread-safe, hehe
The protagonist has set, of course, is the script, we need to set the time for the protagonist to play, here I use the servlet to start the thread, specifically as follows
Package Com.smartsoft.thread;import Java.util.map;public class Servicethreadmap {map<string, Thread> ServiceMap ;p ublic Servicethreadmap (map<string, thread> Servicemap) {super (); this.servicemap = Servicemap;} Public map<string, Thread> Getservicemap () {return servicemap;}}
Package Com.smartsoft.servlet;import Java.util.iterator;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Org.springframework.web.context.webapplicationcontext;import Org.springframework.web.context.support.webapplicationcontextutils;import Com.smartsoft.thread.ServiceThreadMap /** * Activate the registered thread * @author Dan * */public class BootStrapper extends httpservlet{private static final long Serialversionui D = 1l;private webapplicationcontext webapp;private servicethreadmap servicethreadmap;/* (non-Javadoc) * @see Javax.servlet.genericservlet#destroy () */@SuppressWarnings ("deprecation") @Overridepublic void Destroy () {//TODO auto-generated method Stubiterator<thread> service = Servicethreadmap.getservicemap (). values (). iterator (); while (Service.hasnext ()) {Service.next (). Stop ();}} /* (non-javadoc) * @see javax.servlet.genericservlet#init () */@Overridepublic void init () throws Servletexception {//TOD O auto-generated Method Stub//super.init ();//Get WebapplicationcOntext to Like WebApp = Webapplicationcontextutils.getrequiredwebapplicationcontext (Getservletcontext ());//Start send Message Threadservicethreadmap = (servicethreadmap) webapp.getbean ("Servicemap");// Get the list of threads registered in Service-spring.xml iterator<thread> service = Servicethreadmap.getservicemap (). values (). Iterator () ;//Get the thread iterator in the threads list/* * Every thread */while (Service.hasnext ()) {System.out.println ("---------------------------------) in the activation list ------------------"); Service.next (). Start ();}}}
It is important to note that this is written as a map collection because it can be extended to start multiple threads at the same time
Registering thread classes in spring XML
<bean id= "Newgamesetthread" class= "com.smartsoft.thread.NewGameSetThread" ></bean><!--Thread registration -- ><bean id= "Servicemap" class= "Com.smartsoft.thread.ServiceThreadMap" ><constructor-arg index= "0" > <map><!--Dan--><entry key= "Newgamesetthread" value-ref= "Newgamesetthread"/></map></ Constructor-arg></bean>
There is only one thread class to start, as many can be added here
Finally start the servlet with project start in Web. xml
<servlet><servlet-name>bootstrapper</servlet-name><servlet-class> com.smartsoft.servlet.bootstrapper</servlet-class><load-on-startup>1</load-on-startup></ Servlet>
This makes it possible to start the threading service on the Web, or it's pretty simple. Haha, I'm standing on the shoulders of giants.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Web project start thread Service