Sobes.tech
Middle

Kas on võimalik käivitada ainult Runnable või ka Callable kasutades submit?

sobes.tech AI

Vastus AI-lt

The submit method of ExecutorService in Java can accept both Runnable and Callable.

  • If a Runnable is passed, the method returns a Future<?>, which can be used to monitor the completion of the task, but the result will be null.
  • If a Callable<V> is passed, then submit returns a Future<V>, where V is the type of the result returned by the task.

Example:

ExecutorService executor = Executors.newFixedThreadPool(2);

// Runnable
Future<?> future1 = executor.submit(() -> System.out.println("Runnable task"));

// Callable
Future<Integer> future2 = executor.submit(() -> {
    Thread.sleep(1000);
    return 42;
});

Integer result = future2.get(); // result will be 42
executor.shutdown();