most of the functions that use timed execution are done with task scheduling, and single-faced ordering Business/shopping and other such business is not easy to deal with, such as the purchase of order function, in your order management
there are n orders that automatically release items in the cart when the order exceeds 10 minutes of payment and the order is void. This high-frequency delay task re-use task scheduling (timing) implementation is not worth the candle. Java delay queue is recommended, Delayqueue is a class provided in Java.util.concurrent Delayqueue is a unbounded blockingqueue, Used to place objects that implement the delayed interface .
. Note: You cannot place a null element in this queue.
Import Java.util.concurrent.delayed;import Java.util.concurrent.timeunit;import java.util.concurrent.atomic.atomiclong;//task thread implementation delayed interface public class Delayitem<t extends runnable> implements Delayed {//Expiry time private final long time;//Task object Private final T task;//Atomic class private static final Atomiclong atomic = new Atomic Long (0);p rivate final long n;public delayitem (long timeout, T t) {this.time = Systen,nanotime () + timeout; This.task = t; THIS.N = Atomic.getandincrement ();} Returns the remaining delay time associated with this object, expressed in a given time unit, public long Getdelay (timeunit unit) {return Unit.convert (This.time-system.nanotime (), Ti Meunit.nanoseconds);} public int CompareTo (Delayed other) {if (other = = this) {return 0; } if (other instanceof Delayitem) {delayitem<?> x = (delayitem<?>) Other; Long diff = Tiem-x.time; if (diff < 0) {return-1; }else if (diff > 0) {return 1; }else if (n < X.N) {return-1;}else { return 1; } Long D = (Getdelay (timeunit.nanoseconds)-Other.getdelay (timeunit.nanoseconds)); return (d = = 0)? 0: ((d < 0)? -1:1); } public T Gettask () {return this.task; } @Override public int hashcode () {return task.hashcode (); } @Override public Boolean equals (Object object) {if (object instanceof Delayitem) {return object.h Ashcode () = = Hashcode ()? True:false; } return false;}} Manage deferred tasks class import Java.util.map;import Java.util.concurrent.delayqueue;import java.util.concurrent.ExecutorService ; Import Java.util.concurrent.executors;import Java.util.concurrent.timeunit;import org.apache.log4j.logger;// Delay queue holds validity object public class Itemqueuethread {private static final Logger Logger = Logger.getlogger (this.class);p rivate Itemqueuethread () {}//lazy load (thread safe) private static class lazyholder{private static Itemqueuethread Itemqueuethread = new It Emqueuethread ();} public static ItemqueuethreAd getinstance () {return lazyholder.itemqueuethread;} Cache thread pool Executorservice executor = Executors.newcachethreadpool ();//thread private thread daemonthead;//initialize thread public void Init () {daemonthread = new Thread ((), {try{execute (); }CATHC (interruptedexception e) {e.printstacktrace (); Logger.info (E.getmessage ()); } }); System.out.println ("Init......start"); Daemonthread.start ();} private void Execute () throws Interrupedexception {while (true) {map<thread, stacktraceelement[]> Map = T Hread.getallstacktraces (); System.out.println ("Number of threads ...." + map.size ()); System.out.println (System.currenttimemills ()); System.out.println (Item.size ()); SYSTEM.OUT.PRINTLN ("Thread state----" + thread.currentthread (). GetState ()); try{//From the delay queue, if there is no object expiration responsibility queue has been waiting for delayitem<?> T1 = Item.take (); if (T1! = null) {Runnable task = T1.gettask (); if (task = = null) {continue; } executor.execute (Task); }}catch (Exception e) {e.printstacktrace (); Logger.info (E.getmessage ()); }}//creates an empty delay queue private delayqueue<delayitem<?>> item = new delayqueue<> ();//Add task to queue public void put (l Ong time, Runnable task, Timeunit timeunit) {//convert to ns long nanotime = TimeUnit.NANOSECONDS.convert (time,timeunit); delayitem<?> k = new Delayitem (nanotime,task); Item.put (k); _:}//End Task Public boolean endtask (delayitem<runnable> Task) {return Item.remove (Task);}} The function code that needs delay is extracted separately as a class, inheriting Runnable implementation of the Run method public class Datademo implements Runnable {int a =-1; Public Datademo (int i) {this.a = i;} @Overridepublic void Run () {System.out.println ("timeout, order to revoke ...." + a);}} Test Classimport Java.util.random;import java.util.concurrent.timeunit;public class delaytest{public static void Main (string[] args) {ItEmqueuethread ith = itemqueuethread.getinstance (); Ith.init (); Random r = new Random (); for (int i = 0; i < 5; i++) {int a = R.nextint (20); System.out.println ("Pre-known wait time:" + a); Datademo dd = new Datademo (a);//Create a Task object Ith.put (a,dd,timeunit.seconds);//Add task to queue}}}//Note Itemqueuethread's init party method to execute when the container is initialized, or to initialize before the first put delay object task, and run in the Task object when the set delay time expires
Java Delay queue