Example 1: After 3 seconds delay, only 1 times are performed
Scheduledexecutorservice es = Executors.newscheduledthreadpool (5); Log.info ("Start Time"); Try { for(inti = 0; I < 20; i++) {Runnable syncrunnable=NewRunnable () {@Override Public voidrun () {Log.info (Thread.CurrentThread (). GetName ()); } }; Es.schedule (syncrunnable,3000, Timeunit.milliseconds); } } finally{es.shutdown (); }
Operation Result:
10:41:39.589 start time 10:41:42.595 pool-1-thread-1 10:41:42.595 pool-1-thread-2 10:41:42.595 Pool-1-thread-3 10:41:42.595 pool-1-thread-4 10:41:42.596 pool-1-thread-2 10:41:42.596 Pool-1-thread-5 10:41:42.596 pool-1-thread-1 10:41:42.596 pool-1-thread-3 10:41:42.597 Pool-1-thread-4 10:41:42.597 pool-1-thread-2 10:41:42.597 pool-1-thread-5 10:41:42.597 Pool-1-thread-1 10:41:42.598 pool-1-thread-3 10:41:42.598 pool-1-thread-4 10:41:42.598 Pool-1-thread-2 10:41:42.599 pool-1-thread-5 10:41:42.599 pool-1-thread-1 10:41:42.600 Pool-1-thread-3 10:41:42.600 pool-1-thread-4 10:41:42.600 pool-1-thread-2
Threadpoolexecutor of the call:
Public Scheduledthreadpoolexecutor (int corepoolsize) { Super(Corepoolsize, Integer.max_ VALUE, 0, nanoseconds, new delayedworkqueue ()); }
Corepoolsize=5,maximumpoolsize=integer.max_value
Keepalivetime=0 nanoseconds
Allowcorethreadtimeout=false (default)
Use delay queue delayedworkqueue
So
- The number of threads in the thread pool is always 5, permanently surviving
- For new tasks, when the queue is not full, the queue is inserted, and when the queue is full, the default execution AbortPolicy, which throws an exception.
- Support Thread Reuse
So, like Newfixedthreadpool
Public scheduledthreadpoolexecutor (int corepoolsize) {super (corepoolsize, Integer.max_value, 0, nanoseconds, New Delayedworkqueue ()); }
Thread pool (4) executors.newscheduledthreadpool-only executes 1 times