Home  >  Article  >  Java  >  How to implement the Callable interface to create a thread class in java

How to implement the Callable interface to create a thread class in java

PHPz
PHPzforward
2023-05-11 11:58:06897browse

Implement the Callable interface to create a thread class

The Callable interface has been provided since Java5. This interface is an enhanced version of the Runnable interface. The Callable interface provides a call() method as the thread execution body. The call() method There can be a return value, and the call() method can be declared to throw an exception.

  • boolean cancel(boolean may) Try to cancel the associated Callable task in this Future.

  • V get() Return the return value of the call() method in the Call task. Calling this method will cause the thread to block, and you must wait for the child thread to end before getting the return value.

  • V get(long timeout,TimeUnit unit) Return the return value of the call() method in the Call task. This method allows the program to block for up to the time specified by timeout and unit. If the specified time passes, and if there is still no return value after the specified time, a TimeoutException exception will be thrown.

  • boolean isCancelled() Returns true if the Callable task is canceled before it is completed normally.

  • boolean isDone() Returns true if the Callable task has been completed.

Runnable implementation steps:

  1. Create an implementation class of the Callable interface and implement the call() method. The call() The method serves as the execution body of the thread, and the call() method has a return value.

  2. Use the FutureTask class to wrap the Callable object.

  3. Use the FutureTask object as the target of the Thread object to create and start a new thread.

  4. Enable the get() method of the FutureTask object to obtain the return value of the child thread.

public class CallableDemo implements Callable {
   public static void main(String args[]) {
       FutureTask futureTask = new FutureTask(new CallableDemo());
       new Thread(futureTask).start();
       try {
           System.out.println("子线程返回值:" + futureTask.get());
       } catch (InterruptedException e) {
           e.printStackTrace();
       } catch (ExecutionException e) {
           e.printStackTrace();
       }
       if (futureTask.isDone()) {
           System.out.println("线程结束");
       }
   }

   @Override
   public Integer call() throws Exception {
       System.out.println("线程开始");
       int ss = 0;
       for (int i = 0; i < 20; i++) {
           ss += i;
       }
       return ss;
   }
}

The above is the detailed content of How to implement the Callable interface to create a thread class in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete