📜  Java ExecutorService execute() 和 submit() 方法的区别

📅  最后修改于: 2021-09-12 11:31:59             🧑  作者: Mango

ExecutorService 接口通过添加有助于管理和控制线程执行的方法来扩展 Executor。它在Java.util.concurrent 包中定义。它定义了执行返回结果的线程、一组线程和确定关闭状态的方法。在本文中,我们将看到称为 execute() 和 submit() 的两个此类方法之间的区别。

在Java,为了执行异步任务,实现了 runnable 接口。为了做到这一点,一个这样的可用接口是 Executor 接口。执行器接口包含execute()方法。除此之外,还有另一个可用的接口是 ExecutorService 接口,它扩展了 executor 接口。该方法包含 submit() 方法。下图说明了这两个接口之间的关系。

执行方法:此函数在将来的某个时间执行给定的命令。根据 Executor 实现的判断,该命令可以在新线程、池线程或调用线程中执行。此方法是一个 void 方法,这意味着它不返回任何函数。一旦在 execute() 方法中分配了任务,我们将不会得到任何响应,我们可以忘记任务。下面是execute方法的一个实现。

Java
// Java program to demonstrate
// the behavior of the
// execute() method
 
import java.util.concurrent.*;
public class GFG {
 
    public static void main(String[] args)
        throws Exception
    {
 
        // Creating the object of the
        // Executor Service
        ExecutorService executorService
            = Executors.newSingleThreadExecutor();
 
        // execute() method cannot return
        // anything because it's return type
        // is void.
 
        // By using execute(), we are accepting
        // a Runnable task
        executorService.execute(new Runnable() {
 
            // Override the run method
            public void run()
            {
                System.out.println(
                    "This is execute() "
                    + "method example");
            }
        });
 
        // This method performs all the
        // previouslu submitted tasks
        // before termination
        executorService.shutdown();
    }
}


Java
// Java program to demonstrate
// the behavior of the
// submit() method
 
import java.util.concurrent.*;
public class GFG {
    public static void main(String[] args)
        throws Exception
    {
 
        // Creating the object of the
        // Executor service interface
        ExecutorService executorService
            = Executors.newFixedThreadPool(1);
 
        // submit() method can return the
        // result of the computation
        // because it has a return type of Future.
 
        // By using submit(), we are
        // accepting a Callable task
        Future obj
            = executorService.submit(new Callable() {
 
                  // Overriding the call method
                  public Object call()
                  {
                      System.out.println(
                          "This is submit() "
                          + "method example");
 
                      return "Returning Callable "
                          + "Task Result";
                  }
              });
 
        // This method will return the result
        // if the task has finished perfectly.
        // The submit() method returns a
        // Java Future object which is
        // used to check when the Runnable
        // has completed.
        // As it implements Future,
        // get() method is called
        // to get the result
        System.out.println(obj.get());
         executorService.shutdown();
    }
}


输出:

提交方法:该函数在未来的某个时间执行给定的命令。根据 Executor 实现的判断,该命令可以在新线程、池线程或调用线程中执行。与execute 方法不同,此方法返回一个future。在Java,future 表示异步计算的结果。 future 对象用于在执行开始后处理任务。因此,当我们需要执行的结果时,那么我们可以使用future对象的submit()方法。为了得到结果,我们可以在 Future 上使用get()方法。 get() 方法返回一个对象,如果我们在任务完成之前调用 get() 方法,它会阻塞直到结果准备好并可能抛出已检查的异常或者如果任务完成,则未来对象持有一个结果被返回,然后可以在以后使用。以下是提交方法的实现:

Java

// Java program to demonstrate
// the behavior of the
// submit() method
 
import java.util.concurrent.*;
public class GFG {
    public static void main(String[] args)
        throws Exception
    {
 
        // Creating the object of the
        // Executor service interface
        ExecutorService executorService
            = Executors.newFixedThreadPool(1);
 
        // submit() method can return the
        // result of the computation
        // because it has a return type of Future.
 
        // By using submit(), we are
        // accepting a Callable task
        Future obj
            = executorService.submit(new Callable() {
 
                  // Overriding the call method
                  public Object call()
                  {
                      System.out.println(
                          "This is submit() "
                          + "method example");
 
                      return "Returning Callable "
                          + "Task Result";
                  }
              });
 
        // This method will return the result
        // if the task has finished perfectly.
        // The submit() method returns a
        // Java Future object which is
        // used to check when the Runnable
        // has completed.
        // As it implements Future,
        // get() method is called
        // to get the result
        System.out.println(obj.get());
         executorService.shutdown();
    }
}

输出:

下表展示了execute方法和submit方法的区别:

Execute Method Submit Method
This method is declared in the Executor interface. This method is declared in the ExecutorService interface.
This method can accept only runnable task.  This method can accept both runnable and callable tasks.
This method has a return type of void. This method has a return type of Future.
This method is used when we are not bothered about the result but want the code to run in parallel by the worker threads of the thread pool. This method is used when we care about the result and need it from the task which has been executed.