Java Use task schema to perform task scheduling sample _java

Source: Internet
Author: User
Tags static class thread class

Copy Code code as follows:

Package Com.yao;

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 task execution architecture.
* Starting a task before Java 5.0 is implemented by invoking the start () method of the thread class.
* The delivery and execution of the task is simultaneous, if you want to schedule the execution of the task,
* or controlling the number of threads executing concurrently requires additional coding to complete.
* 5.0 provides a new task execution architecture that allows you to easily schedule and control the execution of tasks.
* and you can create a thread pool similar to the database connection pool to perform tasks.
* This architecture consists primarily of three interfaces and their corresponding specific classes.
* These three interfaces are executor, Executorservice and Scheduledexecutorservice.
* (1) Executor interface: is used to perform runnable tasks, it defines only one method:
* Execute (Runnable command): Perform ruannable type of task
* (2) Executorservice: Inherits the Executor method and provides services for performing callable tasks and aborting task execution.
* The main methods of its definition are:
* Submit (Task): can be used to submit callable or runnable tasks, and to return the future object representing this task
* InvokeAll (Collection of tasks): Collection of batch tasks, and returns a collection of future objects representing these tasks
* Shutdown (): Closes a service after a committed task is completed and no longer accepts new tasks
* Shutdownnow (): Stops all executing tasks and closes the service.
* isterminated (): Tests whether all tasks have been executed.
* IsShutDown (): Test if the executorservice has been closed
* (3) Scheduledexecutorservice: Inheriting Executorservice, providing the ability to perform tasks on a schedule,
* Schedule (Task, Initdelay): Schedule the submitted callable or runnable tasks to be performed after the specified time of Initdelay.
* Scheduleatfixedrate (): Schedule the submitted runnable tasks to be repeated at specified intervals
* Schedulewithfixeddelay (): Schedule the submitted runnable task to be repeated after each execution, waiting for the time specified by delay.
*
* Access to a variety of service objects through the Executors class.
* Callable (Runnable Task): Translating Runnable tasks into callable tasks
* Newsinglethreadexecutor: Produces a Executorservice object, this object only one thread can be used to perform the task, if more than one task, the task will be executed sequentially.
* Newcachedthreadpool (): Produces a Executorservice object, this object with a thread pool, the size of the thread pool will be adjusted as needed, the thread after the task to return to the thread pool to perform the next task to use.
* Newfixedthreadpool (int poolsize): Produces a Executorservice object with a thread pool of size poolsize, if the number of tasks is greater than poolsize, Tasks are executed sequentially in a queue.
* Newsinglethreadscheduledexecutor: Produces a Scheduledexecutorservice object that has a thread pool size of 1 and, if more than one task, the task is executed sequentially.
* Newscheduledthreadpool (int poolsize): Produces a Scheduledexecutorservice object, the thread pool size of this object is poolsize, if the number of tasks is greater than poolsize, The task will be in a queue waiting to be executed.
*/
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 interrupted.")
+ System.currenttimemillis ());
}
}
}

/**
* The callable ends another task
*/
public static class Mycallable implements callable {
Private Future Future;

Public mycallable (Future Future) {
This.future = future;
}

Public String call () {
System.out.println ("To Cancell Task ...")
+ +system.currenttimemillis ());
This.future.cancel (TRUE);
Return "Task cancelled!";
}
}

 /**
  * @param args
  * @throws executionexception
  * @throws interruptedexception
  */
 public static void Main (string[] args) throws Interruptedexception,
    executionexception {
  //produces a Executorservice object with a thread pool that adjusts the size of the thread pool as needed
  // After the thread finishes the task, it returns to the thread pool for the next task to be used.
  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 runnable tasks to callable tasks
  callable mythreadcallable = executors.callable (new Mythread ());
  future mythreadcallablefuture = Cachedservice.submit (mythreadcallable);
  //does not return a value for the runnable task after it is converted to a callable task
  system.out.println ( Mythreadcallablefuture.get ());
  cachedservice.shutdownnow ();
  system.out.println ("-----------------");

The

  //produces a Executorservice object with a thread pool of size poolsize,
  //If the number of tasks is greater than poolsize, The task will be placed in a queue to execute
  executorservice fixedservice = Executors.newfixedthreadpool (2);
  fixedservice.submit (New Mythread ());
  fixedservice.submit (New Mythread ());
  //because the thread pool size is 2, the following task must wait for the previous task to finish before it can be executed.
  mythreadfuture = fixedservice.submit (New Mythread ());
  mycallablefuture = fixedservice.submit (new mycallable (mythreadfuture));
  system.out.println (Mycallablefuture.get ());
  fixedservice.shutdownnow ();
  system.out.println ("-----------------");

Produces a Scheduledexecutorservice object that has a thread pool size of poolsize,
If the number of tasks is greater than poolsize, the task waits for execution in a queue
Scheduledexecutorservice Fixedscheduledservice = Executors
. Newscheduledthreadpool (2);
New Task 1
Mythread Task1 = new Mythread ();
Use the task execution service to perform task 1 immediately, and then perform task 1 every 2 seconds thereafter.
Mythreadfuture = fixedscheduledservice.scheduleatfixedrate (Task1, 0, 2,
Timeunit.seconds);
New Task 2
Mycallable task2 = new mycallable (mythreadfuture);
Use the task execution service to wait 5 seconds to perform task 2, and then close task 1 when it is executed.
Mycallablefuture = Fixedscheduledservice.schedule (Task2, 5,
Timeunit.seconds);
System.out.println (Mycallablefuture.get ());
Fixedscheduledservice.shutdownnow ();
}
}

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.