Java concurrency and multithreading 3: Thread Scheduling and conditional cancel Scheduling

Source: Internet
Author: User

Java concurrency and multithreading 3: Thread Scheduling and conditional cancel Scheduling
In article 1st, the "basic example of the concurrency framework" mentioned Executors and ThreadPool.
There is also a "scheduled scheduling" method, Executors. newScheduledThreadPool (10 ).

// A thread pool that can execute scheduling commands (timing + periodicity). It has a fixed number of threads // It is executed repeatedly, and the public static void scheduledThreadPool () {int initialDelay = 10 is endless; int period = 10; Executor executor = Executors. newScheduledThreadPool (10); ScheduledExecutorService scheduler = (ScheduledExecutorService) executor; schedtor. scheduleAtFixedRate (task, initialDelay, period, TimeUnit. SECONDS );}


This code is always executed repeatedly, which is a common scenario.

However, when I think of a requirement of "only scheduling N times", I read the API and didn't provide it.
I searched for "Java canceling Thread Scheduling" on the Internet, found a question and answer, and studied it.
The key to the code example is to use the thread-safe AtomicInteger and the general synchronization tool CountDownLatch.

The core logic is that when the maximum number of tasks is N, the tasks in Future will be canceled. The counter-1 in countDownLatch will be changed to 0, and the thread blocking of "countDownLatch. await ()" will end.
CountDownLatch. countDown ();
For more information about CountDownLatch, see section 4th.

Package cn.fansunion.exe cutorframework; import java. util. hashMap; import java. util. map; import java. util. concurrent. countDownLatch; import java. util. concurrent. executor; import java. util. concurrent. executors; import java. util. concurrent. future; import java. util. concurrent. scheduledExecutorService; import java. util. concurrent. timeUnit; import java. util. concurrent. atomic. atomicInteger; // conditionally cancel public class ConditionCancelSchedulerDemo {public static Runnable task = new Runnable () {@ Overridepublic void run () {System. out. println ("Execute a task") ;}}; // a thread pool with a fixed number of threads that can Execute scheduling commands (timing + periodicity) // run repeatedly, public static void scheduledThreadPool () {int initialDelay = 10; int period = 10; Executor executor = Executors. newScheduledThreadPool (10); ScheduledExecutorService scheduler = (ScheduledExecutorService) executor; schedtor. scheduleAtFixedRate (task, initialDelay, period, TimeUnit. SECONDS);} public static void main (String [] args) throws Exception {scheduledThreadPool (); conditioncancelschedpool ();} private static void conditionCancelScheduler () throws InterruptedException {final String jobID = "my_job_1"; final AtomicInteger count = new AtomicInteger (0); final Map
 
  
Futures = new HashMap <> (); // execute a maximum of 10 tasks, final int maxTaskSize = 10; // more common CountDownLatch Methods, please refer to CountDownLatchDemofinal CountDownLatch countDownLatch = new CountDownLatch (1); ScheduledExecutorService schedch = Executors. newSingleThreadScheduledExecutor (); Future future = schedtor. scheduleWithFixedDelay (new Runnable () {@ Overridepublic void run () {System. out. println (count. getAndIncrement (); // when the scheduling is executed, the max When TaskSize + 1 task, cancel the task in Future. 11th tasks if (count. get ()> maxTaskSize) {System. out. println ("a"); Future f = futures. get (jobID); if (f! = Null) {f. cancel (true);} // counter-1 in countDownLatch, to 0 // "countDownLatch. await () "thread congestion ends countDownLatch. countDown () ;}}, 0, 1, TimeUnit. SECONDS); futures. put (jobID, future); countDownLatch. await (); scheduler. shutdown ();}}
 


More code examples:
Http://git.oschina.net/fansunion/Concurrent (coming soon)

References:
Java concurrent programming-Executor framework
Http://www.iteye.com/topic/366591

Conditional termination of scheduled tasks in ScheduledExecutorService
Http://www.oschina.net/question/1158769_119659? Sort = time

Jdk api documentation

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.