Uczę się używać exectorServices
do gromadzenia threads
i wysyłania zadań. Mam prosty program poniżejRóżnica między executor.submit i executor.execute w tym kodzie w Javie?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Processor implements Runnable {
private int id;
public Processor(int id) {
this.id = id;
}
public void run() {
System.out.println("Starting: " + id);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("sorry, being interupted, good bye!");
System.out.println("Interrupted "+Thread.currentThread().getName());
e.printStackTrace();
}
System.out.println("Completed: " + id);
}
}
public class ExecutorExample {
public static void main(String[] args) {
Boolean isCompleted=false;
ExecutorService executor = Executors.newFixedThreadPool(2);
for(int i=0; i<5; i++) {
executor.execute(new Processor(i));
}
//executor does not accept any more tasks but the submitted tasks continue
executor.shutdown();
System.out.println("All tasks submitted.");
try {
//wait for the exectutor to terminate normally, which will return true
//if timeout happens, returns false, but this does NOT interrupt the threads
isCompleted=executor.awaitTermination(100, TimeUnit.SECONDS);
//this will interrupt thread it manages. catch the interrupted exception in the threads
//If not, threads will run forever and executor will never be able to shutdown.
executor.shutdownNow();
} catch (InterruptedException e) {
}
if (isCompleted){
System.out.println("All tasks completed.");
}
else {
System.out.println("Timeout "+Thread.currentThread().getName());
}
}
}
To nie robi nic nadzwyczajnego, ale tworzy dwa threads
i przedkłada 5 Zadania w sumie. Po wykonaniu każdego z nich thread
zajmuje następną, W powyższym kodzie używam executor.submit
. Zmieniłem także na executor.execute
. Ale nie widzę żadnej różnicy w wynikach. Czym różnią się metody submit and execute
? To co API
mówi
Sposób przedstawienia rozciąga metoda baza Executor.execute (java.lang.Runnable) poprzez tworzenie i powrocie do przyszłości, które mogą być wykorzystane, aby anulować wykonanie i/lub poczekać na zakończenie. Metody invokeAny i invokeAll wykonują najczęściej używane formy masowego wykonywania, wykonując zbiór zadań, a następnie czekając na ukończenie co najmniej jednego lub wszystkich. (Klasa ExecutorCompletionService może być używana do pisania dostosowanych wariantów tych metod.)
Ale nie jest dla mnie jasne, co to dokładnie oznacza? Dzięki
użyteczne pytanie. Warto umieścić go tutaj. – MKod