Learn Java Multi-Threading 9-timed task instances with examples

Source: Internet
Author: User

Timed tasks are often the business scenarios we encounter, we have a lot of features need such technology to achieve, such as: timed to get some data push out, timed to deal with some cleanup tasks, check a certain value, etc. So how do we do it, and what should we pay attention to in the implementation?

Timing task is another thread to execute, in fact, is also a class of concurrency, we may not understand, said timing is to the time to execute, how to produce concurrency, here is mainly to see two indicators, one is to see the frequency of execution, the second is to look at the time of each execution, if the implementation of high frequency and task will be time-consuming Then there is the concurrency, and of course there is the case that the method of invoking other services in a timed job, while the normal business logic also calls the method of that service, then it is possible to have concurrency at some coincidental time.

So we should also pay attention to this two points when we write a timed task:

1: If the execution frequency is high and the execution of the task is time consuming, the execution method of the job should be synchronously processed.

2: If the job calls other service methods, the methods provided by other services are also guaranteed to be published as thread-safe methods.

Let's take a look at a few ways to implement timed tasks:

1:java provided by the timer

Package Com.home.thread.thread10;import java.util.date;import java.util.timer;/** * @author Gaoxu * Practice a genuine knowledge! */public class Timermain {/** * @param args */public static void main (string[] args) {Timer timer = new Timer (); Timer.sche Dule (New Timertaskthread (), New Date (), 2000);}}


Package Com.home.thread.thread10;import java.util.date;import java.util.timertask;/** * @author Gaoxu * Practice a genuine knowledge! */public class Timertaskthread extends timertask{//constructor with no arguments public timertaskthread () {}//can also write a constructor with parameters @overridepublic synchronized void Run () {System.out.println (New Date (). toString () + "timer mode, I am two seconds to execute once");//Here you can write the timer business you want to implement}}

This is a timed task that is implemented by a timer and runs as follows:

Sat. 01:25:31 CST 2015,timer mode, I was two seconds to execute a Sat Feb 01:25:33 CST 2015,timer Way, I was two seconds to perform a Sat Feb 01:25:35 CST 2015,tim Er way, I was two seconds to execute a sat Feb 01:25:37 CST 2015,timer Way, I was two seconds to execute once

2: Timed tasks implemented by the open source framework Quartz

Package Com.home.thread.thread10;import Org.quartz.scheduler;import Org.quartz.schedulerexception;import Org.quartz.schedulerfactory;import org.quartz.impl.stdschedulerfactory;import com.home.JobServiceImpl;/** * @ Author Gaoxu * Practice the truth! */public class Schedulermain {public static void main (string[] para) {try {schedulerfactory SF = new Stdschedulerfactory () ; Scheduler Scheduler = Sf.getscheduler (); Jobserviceimpl jobservice = new Jobserviceimpl (); Jobservice.setscheduler (scheduler); Jobservice.platdatacollectinterval (2);} catch (Schedulerexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (Exception e) {//Todo Auto-ge Nerated catch Blocke.printstacktrace ();}}}


Package Com.home;import Org.quartz.jobbuilder;import Org.quartz.jobdetail;import org.quartz.scheduler;import Org.quartz.schedulerexception;import Org.quartz.simpleschedulebuilder;import Org.quartz.Trigger;import Org.quartz.triggerbuilder;import com.home.job.testjob;/** * @author Gaoxu * Practice a genuine knowledge! */public class Jobserviceimpl {private Scheduler scheduler;public void Setscheduler (Scheduler Scheduler) { This.scheduler = Scheduler;} Public Scheduler Getscheduler () {return Scheduler;}  public void Platdatacollectinterval (int interval) throws Schedulerexception, Exception {System.out.println ("update Platdatacollect cycle start "); Jobdetail Jobdetail = Jobbuilder.newjob (Testjob.class). Withidentity ("Testjob_1", "group_1"). Build (); Trigger Trigger = Triggerbuilder.newtrigger (). Withidentity ("trigger_1", "Group_1"). Withschedule ( Simpleschedulebuilder.repeatsecondlyforever (interval)). build (); Scheduler.schedulejob (Jobdetail, Trigger); Scheduler.start ();}}

Package Com.home.job;import Java.util.date;import Org.quartz.job;import org.quartz.jobexecutioncontext;import Org.quartz.jobexecutionexception;public class Testjob implements job{@Overridepublic void execute ( Jobexecutioncontext arg0) throws Jobexecutionexception {System.out.println ("Test Job Date:" + new Date (). toString ()); c0/>}}


There are three classes, where the job class is the performer of the task, Scheduler is a scheduler, and the scheduler can create multiple trigger, each trigger can execute a job.

Log4j:warn No Appenders could is found for logger (org.quartz.impl.StdSchedulerFactory). Log4j:warn Please initialize the L og4j system Properly.log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.update  Platdatacollect cycle starttest job Date:sat Feb 01:30:31 CST 2015test job Date:sat Feb 01:30:33 CST 2015test job da Te:sat Feb 01:30:35 CST 2015test job Date:sat Feb 01:30:37 CST 2015


3: is a thread to implement

Package com.home.thread.thread10;/** * @author Gaoxu * Practice the truth! */public class ThreadMain {public static void main (string[] para) {threadtask threadtask = new Threadtask (); Threadtask.sta RT ();}}



Package Com.home.thread.thread10;import Java.util.date;public class Threadtask extends thread{public void run () {while ( True) {try {thread.sleep (2000); System.out.println (New Date (). toString () + "thread mode, I am two seconds to execute");//Here you can write the timer business you want to implement} catch (Interruptedexception e) { E.printstacktrace ();}}}


Operation Result:

Sat 01:33:34 CST 2015 thread Way, I was two seconds to execute a Sat Feb 01:33:36 CST 2015 thread Way, I was two seconds to execute a Sat Feb 01:33:38 CST 2015 thread Way, I was two seconds to perform a Sat 01:33:40 CST 2015 thread Way, I was two seconds to execute a Sat Feb 01:33:42 CST 2015 thread Way, I was two seconds to execute once


There are many ways to accomplish tasks, such as Java.util.concurrent.ScheduledThreadPoolExecutor, where there are no examples.

It is important to note the concurrency of timed tasks to avoid concurrency errors.





Learn Java Multi-Threading 9-timed task instances with examples

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.