Java multi-thread task execution architecture

Source: Internet
Author: User
Import Java. util. concurrent. callable; import Java. util. concurrent. executionexception; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; import Java. util. concurrent. future; import Java. util. concurrent. scheduledexecutorservice; import Java. util. concurrent. timeunit;/*** new job execution architecture. * Before Java 5.0, a task is started by calling the START () method of the thread class. * The task is submitted and executed simultaneously, if you want to schedule the task execution, * or control the number of concurrent threads, you need to write additional code. * 5.0 provides a new task execution architecture that allows you to easily schedule and control task execution. * You can create a thread pool similar to a database connection pool to execute tasks. * This architecture consists of three interfaces and corresponding classes. * The three interfaces are executor, executorservice, and scheduledexecutorservice. * (1) executor interface: used to execute a runnable task. It defines only one method: * execute (runnable command): execute a ruannable task * (2) executorservice: it inherits the executor method and provides services for executing callable tasks and suspending task execution. * The methods defined are as follows: * submit (task ): can be used to submit callable or runnable tasks, and return the future object * invokeall (collection of tasks) representing this task: a collection of batch processing tasks, return a future object set * Shutdown () representing these tasks: Close the service after the submitted tasks are completed, and no longer accept the new task * shutdownnow (): stop all ongoing tasks and close services. * Isterminated (): test whether all tasks have been completed. * Isshutdown (): test whether the executorservice has been disabled * (3) scheduledexecutorservice: inherits the executorservice and provides the time-based task execution function. * Schedule (task, initdelay ): schedule the submitted callable or runnable tasks to be executed after the time specified by initdelay. * Scheduleatfixedrate (): schedules repeated execution of submitted runnable tasks at specified intervals * schedulewithfixeddelay (): schedules submitted runnable tasks after each execution, wait for the time specified by delay to be repeated. ** The executors class is used to obtain various service objects. * Callable (runnable task): converts a runnable task to a callable task * newsinglethreadexecutor: generates an executorservice object. This object has only one thread to execute the task. If there are more than one task, tasks are executed sequentially. * Newcachedthreadpool (): generates an executorservice object with a thread pool. The size of the thread pool is adjusted as needed. After the thread executes the task, it returns to the thread pool, used to execute the next task. * Newfixedthreadpool (INT poolsize): generates an executorservice object with a poolsize thread pool. If the number of tasks is greater than poolsize, the task is executed sequentially in a queue. * Newsinglethreadscheduledexecutor: generates a scheduledexecutorservice object. The thread pool size of this object is 1. If there are more than one task, the task will be executed in sequence. * Newscheduledthreadpool (INT poolsize): generates a scheduledexecutorservice object whose thread pool size is poolsize. If the number of tasks is greater than poolsize, the task will wait for execution in a queue */public class executearch {/*** this thread outputs a line of strings */public static class mythread implements runnable {public void run () {system. out. println ("task repeating. "+ system. currenttimemillis (); try {thread. sleep (1000);} catch (interruptedexception e) {system. out. println ("task interrupt Ed. "+ system. currenttimemillis () ;}}/ *** the callable end another task */public static class mycallable implements callable {private future; Public mycallable (Future) {This. future = Future;} Public String call () {system. out. println ("to cancell task... "++ system. currenttimemillis (); this. future. cancel (true); Return "task canceled! ";}}/*** @ Param ARGs * @ throws executionexception * @ throws interruptedexception */public static void main (string [] ARGs) throws interruptedexception, executionexception {// generate an executorservice object with a thread pool. The thread pool size will be adjusted as needed. // return to the thread pool after the thread finishes executing the task, used to execute the next task. Executorservice cachedservice = executors. newcachedthreadpool (); Future mythreadfuture = cachedservice. submit (New mythread (); Future mycallablefuture = cachedservice. submit (New mycallable (mythreadfuture); system. out. println (mycallablefuture. get (); system. out. println ("-----------------"); // converts a runnable task to a callable task callable mythreadcallable = executors. callable (New mythread (); Future mythreadcallablef Uture = cachedservice. submit (mythreadcallable); // For a runnable task, after being converted to a callable task, no system is returned. out. println (mythreadcallablefuture. get (); cachedservice. shutdownnow (); system. out. println ("-----------------"); // generates an executorservice object with a poolsize thread pool. // if the number of tasks is greater than poolsize, the task will be placed in a queue to execute executorservice fixedservice = executors sequentially. newfixedthreadpool (2); fixedservice. submit (New mythread (); fixedservice. s Ubmit (New mythread (); // because the thread pool size is 2, subsequent tasks must be executed after the previous tasks are executed. Mythreadfuture = fixedservice. submit (New mythread (); mycallablefuture = fixedservice. submit (New mycallable (mythreadfuture); system. out. println (mycallablefuture. get (); fixedservice. shutdownnow (); system. out. println ("-----------------"); // generates a scheduledexecutorservice object whose thread pool size is poolsize. // if the number of tasks is greater than poolsize, the task will wait for the execution of scheduledexecutorservice fixedscheduledservice = executors in a queue. newscheduledthreadp OOl (2); // create Task 1 mythread task1 = new mythread (); // use the task execution service to immediately execute Task 1, and then execute Task 1 every 2 seconds. Mythreadfuture = fixedscheduledservice. scheduleatfixedrate (task1, 0, 2, timeunit. seconds); // create Task 2 mycallable task2 = new mycallable (mythreadfuture); // use task execution service to wait for 5 seconds before Task 2 is executed. After Task 1 is executed, Task 1 is disabled. Mycallablefuture = fixedscheduledservice. Schedule (task2, 5, timeunit. Seconds); system. Out. println (mycallablefuture. Get (); fixedscheduledservice. shutdownnow ();}}
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.