ExecutorService in Java

ExecutorService ( Java’s thread pool framework) –

In java, its always being easy to run a method or a piece of code asynchronously.

For Example –

In java, thread can be created in two ways,
1) By extending Thread class
2) By implementing Runnable Interface

If we want to execute a task asynchronously, than we can create a new instance of thread and assign the task to it. And start the thread, it will execute asynchronously.

Task can be executed asynchronously using threads. But, if suppose we want to execute 100000 tasks than we have to create 100000 threads. And each thread can execute one task at a time asynchronously. But, creating 100000 threads for each task is not the feasibile solution.

The Java ExecutorService is the interface which allows us to execute tasks on threads asynchronously. The Java ExecutorService interface is present in the java.util.concurrent package. The ExecutorService helps in maintaining a pool of threads and assigns them tasks. It also provides the facility to queue up tasks until there is a free thread available if the number of tasks is more than the threads available.

By using Executor service, we can create the pool of threads.

ExecutorService executorService = Executors.newFixedThreadPool(10);

Here, we are creating a pool of 10 threads. And 100000 tasks are submitted to the executor service. Internally, it assigns each task to the threads present in the thread pool. Max 10 threads can execute the task at a time. And the tasks are stored in the blocking queue.

Why Blocking Queue ? – Because No two threads can access the queue at the same time.

Once the threads execution completes, it fetches the next task from the blocking queue. And subsequently, all the threads present in the thread pool do the same.

原文链接:ExecutorService in Java

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容