Quin és el marc Executor en java?

The Executor Framework has been introduced in Java 1.5 and it is a part of java.util.concurrent package. The Executor framework is an abstraction over the actual implementation of java multithreading. It is used for standardizing invocation, scheduling, execució i control de les tasques asíncrones d'acord amb un conjunt de polítiques d'execució definit durant la creació de la constructora.

Abans de Java 1.5, aplicacions multithreading es van crear utilitzant grup de fils , grup de subprocessos o grup de subprocessos personalitzada. Ara el control de cada fil ha de ser fet pel programador tenint en compte els següents punts
● Sincronització
● Bloqueig
● Notificació
● bloqueig Dead
I molts més que sorgeix de l'exigència de l'aplicació. Some time it is very difficult to control multithreading applications because the behaviors of the threads are also dependent on the environment where the application is deployed and running. For example the processor speed, the RAM size, the band width all has a direct effect on the multithreading application. So you have to keep all these factors in mind before creating architecture.
An Executor framework provides multi-threading application programs with a easy abstraction for thinking about tasks. Instead of thinking in terms of threads, an application now deals simply with instances of Runnable (which is basically collections of tasks). And then it is passed to an Executor to process. La interfície ExecutorService amplia la interfície Executor simplista i hi ha mètodes de cicle de vida per gestionar el marc executor.
El marc Executor representa tasques mitjançant l'ús de les instàncies de Executable o Exigible. Cursa del Executable () mètode no retorna un valor o llançar una excepció comprovada. Rescatable és una versió més funcional en aquesta àrea. Defineix una trucada () mètode que permet el retorn d'algun valor calculat que es pot utilitzar en el processament futur. I és també una excepció en cas de necessitat.
La classe FutureTask s'utilitza per obtenir informació futura sobre el processament. Una instància d'aquesta classe pot embolicar aviat un rescatable o un executable. Vostè pot obtenir una instància d'aquest com el valor de retorn de presentar () mètode d'un ExecutorService. També pot embolicar manualment la seva tasca en un FutureTask abans de cridar a executar () mètode.
Els següents són els passos per implementar la funció ThreadPoolExecutor.
● Es crea un grup de fil múltiple / senzill.
● Una cua es crea la celebració de totes les tasques, però aquestes tasques encara no s'assignen a les discussions de la piscina. Delimitades i les cues no acotats estan disponibles.
● gestor de rebuig s'utilitza per manejar la situació quan una o més tasques no són capaços d'assignar a la cua. D'acord amb la política de rebuig per defecte, serà simplement llançar una excepció en temps d'execució RejectedExecutionException, i l'aplicació pot agafar-lo o descartar-.

A continuació es presenta un exemple per observar el cicle de vida d'un marc executor. Aquí només parlarem dels passos bàsics i les interfícies bàsiques. There are many more properties and subclasses available to handle different kind of applicant need.

The following class implements Runnable and its instances will be used as a task in the next section of code.

public class jobPrint implements Runnable {
private final String name;
private final int delay;
public jobPrint(String name, int delay) {
this.name = name;
this.delay = delay;
}
public void run() {
System.out.println("Starting: " + name);
try {
Thread.sleep(delay);
} catch (InterruptedException ignored) {
}
System.out.println("Done with: " + name);
}
}

The following class is implementing the executor tasks.

import java.util.concurrent.*;
import java.util.Random;

public class UseExecutorService {
public static void principal(String args[]) {
Random random = new Random();
ExecutorService executor = Executors.newFixedThreadPool(3);
// Sum up wait times to know when to shutdown
int waitTime = 500;
per (int i=0; jo<10; i ) {
String name = “NamePrinter ” + jo;
int time = random.nextInt(1000);
waitTime = time;
Runnable runner = new jobPrint(nom, time);
System.out.println(“Adding: ” + nom + ” / ” + time);
executor.execute(runner);
}
tractar de {
Thread.sleep(waitTime);
executor.shutdown();
executor.awaitTermination
(waitTime, TimeUnit.MILLISECONDS);
} agafar (InterruptedException ignored) {
}
System.exit(0);
}
}

Create an executor

First create an instance of an Executor or ExecutorService. The Executors class has a number of static factory methods to create an ExecutorService. For example, newFixedThreadPool() returns a ThreadPoolExecutor instance with an initialized and unbounded queue and a fixed number of threads. And newCachedThreadPool () returns a ThreadPoolExecutor instance initialized with an unbounded queue and unbounded number of threads. In the 2nd case, existing threads are reused if available.If no free thread is available, a new one is created and added to the pool. Threads that have been idle for longer than a timeout period will be removed automatically from the pool.
This is a fixed pool of 15 threads.
private static final Executor executor = Executors.newFixedThreadPool(15);
This is a cached thread pool
private static ExecutorService exec = Executors.newCachedThreadPool();
Following is a customized thread pool executor. The parameter values depend upon the application need. Here the core pool is having 5 threads which can run concurrently and the maximum number is 10. The queue is capable of keeping 200 tasks. Here one point should be remembered that the pool size should be kept on a higher side to accommodate all tasks. The idle time limit is kept as 5 ms.
private static final Executor executor = new ThreadPoolExecutor(5, 10, 50000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(200));

Create one or more tasks and put in the queue

Create one or more tasks to be performed as instances of either Runnable or Callable.

Submit the task to the Executor

After creating the ExecutorService, you need to submit a task to it by using either submit () or execute () mètode. Now a free thread from the pool will automatically take the tasks from the queue and execute it. Now the process will continue till all the tasks are finished from the queue.

Execute the task

Now the Executor is responsible for managing the task’s execution, thread pool and queue. If the pool has less than its configured number of minimum threads, new threads will be created to handle queued tasks until that limit is reached to the configured value. If the number is higher than the configured minimum, then the pool will not start any more threads. Instead, the task is queued until a thread is freed up to process the request. If the queue is full, then a new thread is started to handle it.

Shutdown the Executor

The termination is executed by invoking its shutdown () mètode. You can choose to terminate it gracefully, or abruptly.

One thought on “Quin és el marc Executor en java?

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share