Java custom task classes perform tasks regularly sample callable and future interface usage _java

Source: Internet
Author: User

Callable and future interfaces

Callable are interfaces similar to runnable, classes that implement callable interfaces, and classes that implement runnable are tasks that can be performed by other threads.

There are several differences between callable and runnable:
(1) The method prescribed by callable is call (), and the Runnable method is run ().
(2) A callable task can return a value after execution, and a runnable task cannot return a value.
(3) The call () method throws an exception, and the run () method cannot throw an exception.
(4) Run callable task to get a future object, future represents the result of an asynchronous computation.

It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to retrieve the results of the calculation.
The future object allows you to understand the execution of a task, cancel the execution of the task, and get the results of the task execution.


Copy Code code as follows:

Package Com.yao;

Import java.util.concurrent.Callable;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;

public class Callableandfuture {

/**
* Customize a task class to implement the callable interface
*/
public static class Mycallableclass implements callable {
Sign bit
private int flag = 0;

Public mycallableclass (int flag) {
This.flag = Flag;
}

  public String Call () throws Exception {
   if (This.flag = = 0) {
     //if the value of flag is 0, it immediately returns
    return "flag = 0";
  &NBSP}
   if (This.flag = = 1) {
    //if the value of flag is 1, do an infinite loop
    try {
     while (true) {
       system.out.println ("looping ...");
      thread.sleep (2000);
     }
    } catch (Interruptedexception e) {
     system.out.println ("interrupted");
    }
    return "false";
   } else {
    //falg is not 0 or 1, throws an exception
    throw new Exception ("Bad flag value!");
   }
  }
 }

public static void Main (string[] args) {
Define 3 callable Types of tasks
Mycallableclass Task1 = new Mycallableclass (0);
Mycallableclass task2 = new Mycallableclass (1);
Mycallableclass task3 = new Mycallableclass (2);

Create a service to perform a task
Executorservice es = Executors.newfixedthreadpool (3);
try {
Commits and executes a task that returns a future object when the task starts.
If you want the result of a task execution or an exception, you can manipulate the future object
Future future1 = Es.submit (TASK1);
Gets the result of the first task, and if the Get method is called, the current thread waits until the task is finished executing
System.out.println ("Task1:" + future1.get ());

Future Future2 = Es.submit (TASK2);
Wait 5 seconds before stopping the second task. Because the second task is an infinite loop.
Thread.Sleep (5000);
System.out.println ("Task2 Cancel:" + Future2.cancel (true));

Gets the output of the third task because performing a third task causes an exception
So the following statement will cause the exception to be thrown
Future future3 = Es.submit (TASK3);
System.out.println ("TASK3:" + future3.get ());
catch (Exception e) {
System.out.println (E.tostring ());
}
Stop the Task Execution service
Es.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.