Java timed boot thread

Source: Internet
Author: User

Here are two ways to start a thread after a specified time. One is realized through Java.util.concurrent.DelayQueue, and the other is realized by Java.util.concurrent.ScheduledThreadPoolExecutor.
1. Java.util.concurrent.DelayQueue
The class Delayqueue is an unbounded blocking queue that extracts elements only when the delay expires. It accepts an instance of the implementation delayed interface as an element.
<<interface>>delayed.java

 Package java.util.concurrent; import java.util.*;  Public Interface extends Comparable<delayed> {    long  getdelay (timeunit unit);}

Getdelay () returns the remaining delay time associated with this object, expressed in a given time unit. The implementation of this interface must define a CompareTo method that provides a consistent ordering of the Getdelay methods of this interface.

The head of the Delayqueue queue is the Delayed element with the longest save time after the delay expires. An expiration occurs when an element's Getdelay (Timeunit.nanoseconds) method returns a value that is less than or equal to 0.
2. Design a queue with time delay characteristics
The class Delayedtasker maintains a delayqueue<delayedtask> queue where Delayedtask implements the delayed interface and is defined by an inner class. Both the outer class and the inner class implement the Runnable interface, and for an external class, its Run method is to remove the tasks in the queue by the defined time, which is an instance of the inner class, and the run method of the inner class defines the specific logic for each thread.

The essence of this design is to define a thread task list with time characteristics, and the list can be of any length. Specify a startup time each time you add a task.
Delayedtasker.java

 PackageCom.zj.timedtask;Import StaticJava.util.concurrent.TimeUnit.SECONDS;Import StaticJava.util.concurrent.TimeUnit.NANOSECONDS;Importjava.util.Collection;Importjava.util.Collections;ImportJava.util.Random;ImportJava.util.concurrent.DelayQueue;Importjava.util.concurrent.Delayed;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.TimeUnit; Public classDelayedtaskerImplementsRunnable {delayqueue<DelayedTask> queue =NewDelayqueue<delayedtask>();  Public voidAddTask (Delayedtask e) {queue.put (e); }     Public voidRemovetask () {queue.poll (); }     PublicCollection<delayedtask>getalltasks () {returncollections.unmodifiablecollection (queue); }     Public intgettaskquantity () {returnqueue.size (); }     Public voidrun () { while(!queue.isempty ())Try{queue.take (). run (); } Catch(interruptedexception e) {System.out.println ("Interrupted"); } System.out.println ("Finished Delayedtask"); }     Public Static classDelayedtaskImplementsDelayed, Runnable {Private Static intCounter = 0; Private Final intid = counter++; Private Final intDelta; Private Final LongTrigger;  PublicDelayedtask (intdelayinseconds) {Delta=Delayinseconds; Trigger= System.nanotime () +Nanoseconds.convert (delta, SECONDS); }        Public Longgetdelay (timeunit unit) {returnUnit.convert (Trigger-system.nanotime (), nanoseconds); }        Public intcompareTo (Delayed Arg) {Delayedtask that=(Delayedtask) arg; if(Trigger <That.trigger)return-1; if(Trigger >That.trigger)return1; return0; }        Public voidrun () {//Run All this want to doSystem.out.println ( This); }        PublicString toString () {return"[" + Delta + "s]" + "Task" +ID; }    }     Public Static voidMain (string[] args) {Random rand=NewRandom (); Executorservice exec=Executors.newcachedthreadpool (); Delayedtasker Tasker=NewDelayedtasker ();  for(inti = 0; I < 10; i++) Tasker.addtask (NewDelayedtask (Rand.nextint (5)));       Exec.execute (Tasker);    Exec.shutdown (); }}

Results:
[0s] Task 1
[0s] Task 2
[0s] Task 3
[1s] Task 6
[2s] Task 5
[3s] Task 8
[4s] Task 0
[4s] Task 4
[4s] Task 7
[4s] Task 9
Finished Delayedtask

3. Java.util.concurrent.ScheduledThreadPoolExecutor
This class can be scheduled to run a task (thread) after a given delay, or to perform a task periodically (repeatedly). You need to know the size of the thread pool in the constructor. The most important methods are:

[1] Schedule

Publicscheduledfuture<?> Schedule (Runnable command,LongDelay,timeunit unit)

Creates and executes a one-time operation that is enabled after a given delay.
Designated by:
-Schedule in the interface Scheduledexecutorservice;
Parameters:
-command-the task to be performed;
-delay-time to delay execution from now on;
-unit-The time unit of the delay parameter;
Return:
-Represents the scheduledfuture of the pending task completion, and its get () method returns NULL when completed.

[2] Scheduleatfixedrate

 public  scheduledfuture<?> Scheduleatfixedrate (Runnable command,  long  initialdelay,long  period,timeunit Unit) 

Creates and executes a recurring action that is first enabled after a given initial delay, with a given period of time, that is, the execution begins after InitialDelay, then executes after Initialdelay+period, followed by InitialDelay + 2 * Period After execution, and so on. If any one execution of the task encounters an exception, subsequent executions are canceled. Otherwise, the task can only be terminated by executing the cancellation or termination method of the program. If any one execution of this task takes longer than its period, subsequent executions will be deferred, but will not be executed at the same time.
Designated by:
-Scheduleatfixedrate in the interface Scheduledexecutorservice;
Parameters:
-command-the task to be performed;
-initialdelay-delay time for first execution;
-period-the period between successive executions;
The time units of the-unit-initialdelay and period parameters;
Return:
-Represents the scheduledfuture of the pending task completion, and its get () method throws an exception after the cancellation.
4. Designing thread performers with time-delay characteristics
Class Scheduletasked associates a scheduledthreadpoolexcutor that can specify the size of the thread pool. The thread pool is closed by the shutdown method through the schedule method knowing the thread and the delay time. The logic for a specific task (thread) has some flexibility (compared to the previous design, the previous design must define the thread's logic beforehand, but can modify the thread-specific logic design by inheriting or decorating).
Scheduletasker.java

 PackageCom.zj.timedtask;ImportJava.util.concurrent.ScheduledThreadPoolExecutor;ImportJava.util.concurrent.TimeUnit; Public classScheduletasker {Private intCorepoolsize = 10;    Scheduledthreadpoolexecutor Scheduler;  PublicScheduletasker () {Scheduler=NewScheduledthreadpoolexecutor (corepoolsize); }     PublicScheduletasker (intquantity) {Corepoolsize=quantity; Scheduler=NewScheduledthreadpoolexecutor (corepoolsize); }     Public voidSchedule (Runnable event,Longdelay)    {Scheduler.schedule (event, delay, timeunit.seconds); }     Public voidshutdown () {scheduler.shutdown (); }     Public Static voidMain (string[] args) {Scheduletasker tasker=NewScheduletasker (); Tasker.schedule (NewRunnable () { Public voidrun () {System.out.println ("[1s]task 1"); }       }, 1); Tasker.schedule (NewRunnable () { Public voidrun () {System.out.println ("[2s]task 2"); }       }, 2); Tasker.schedule (NewRunnable () { Public voidrun () {System.out.println ("[4s]task 3"); }       }, 4); Tasker.schedule (NewRunnable () { Public voidrun () {System.out.println ("[10s]task 4"); }       }, 10);    Tasker.shutdown (); }}

Results:
[1s] Task 1
[2s] Task 2
[4s] Task 3
[10s] Task 4

This article is from the "sub-larvae" blog, make sure to keep this source http://zhangjunhd.blog.51cto.com/113473/74646

Java timed boot thread

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.