ExecutorService
such a need has disappeared.ExecutorService
executes asynchronous code in one or more threads. Creating an ExecutorService instance is done either manually through specific implementations ( ScheduledThreadPoolExecutor
or ThreadPoolExecutor
), but it will be easier to use the Executors
class factory. For example, if you need to create a pool with 2 threads, this is done like this:ExecutorService service = Executors.newFixedThreadPool(2);
ExecutorService service = Executors.newCachedThreadPool();
ExecutorService service = Executors.newCachedThreadPool();
for ( int i = 0; i < 10; i++) {
service.submit( new Runnable() {
public void run() {
// snip... piece of code
}
});
}
submit
method also returns a Future
object that contains information about the execution status of the passed Runnable
or Callable
(which can return a value). From it, you can find out whether the transferred code has completed successfully, or whether it is still being executed. Calling the get
method on the Future
object will return a value that returns Callable
(or null
if Runnable
used). The method has 2 checked-exceptions: InterruptedException
, which is thrown when execution is interrupted via the interrupt()
method, or ExecutionException
if the code in Runnable
or Callable
threw a RuntimeException
, which solves the problem of supporting exceptions between threads.ScheduledExecutorService
comes to the rescue. It allows you to put the code to run in one or more threads and configure the interval or time for which the execution will be delayed. The interval can be the time between two consecutive starts or the time between the end of one execution and the beginning of another. The ScheduledExecutorService
methods return a ScheduledFuture
, which also contains the deferral value for running the ScheduledFuture
.ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.schedule( new Runnable() { ... }, 5, TimeUnit.SECONDS);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate( new Runnable() { ... }, 0, 1, TimeUnit.SECONDS);
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleWithFixedDelay( new Runnable() { ... }, 0, 1, TimeUnit.SECONDS);
Source: https://habr.com/ru/post/116363/
All Articles