Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Java Executor framework

2025-04-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use the Java Executor framework". In the daily operation, I believe many people have doubts about how to use the Java Executor framework. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts about how to use the Java Executor framework. Next, please follow the editor to study!

Most concurrency is achieved through task execution. There are generally two ways to perform tasks: serial and parallel.

Class SingleThreadWebServer {public static void main (String [] args) throws Exception {ServerSocket socket = new ServerSocket (80); while (true) {Socket conn = socket.accept (); handleRequest (conn);} class ThreadPerTaskWebServer {public static void main (String [] args) throws Exception {ServerSocket socket = new ServerSocket (80) While (true) {final Socket conn = socket.accept (); Runnable task = new Runnable () {public void run () {handleRequest (conn);}}; new Thread (task). Start ();}

Of course, both of the above methods are problematic. The problem with single-threading is that concurrency will be the bottleneck, and the creation thread based on the multi-threaded version will lead to insufficient resources.

Executor framework

A task is a set of logical units of work, and threads are the mechanism by which tasks are executed asynchronously.

JDK provides an Executor interface:

Public interface Executor {void execute (Runnable command);}

Although the Executor interface is relatively simple, it is the basis of the asynchronous task execution framework, which can support many different types of task execution strategies. It provides a standard way to decouple the task submission process from the execution process. Use Runnable to represent the task. The implementation of Executor provides support for life cycle and statistical application management and other mechanisms.

Executor is based on the producer-consumer model, where the operation of submitting a task is equivalent to the producer, and the thread executing the task is equivalent to consumption.

Examples of Executor-based WebServer are as follows:

Public class TaskExecutorWebServer {private static final int NTHREADS = 100; private static final Executor exec = Executors.newFixedThreadPool (NTHREADS); public static void main (String [] args) throws Exception {ServerSocket serverSocket = new ServerSocket (80); while (true) {final Socket conn = serverSocket.accept () Runnable task = new Runnable () {@ Override public void run () {handleRequest (conn);}}; exec.execute (task);}

In addition, you can implement Executor to control whether it is concurrent or parallel, as shown in the following code:

/ * object that executes the submitted Runnable task. * this interface provides a way to separate task submission from the mechanism of how each task will run (including details of thread usage, scheduling, etc.). * it is common to use Executor instead of explicitly creating threads. * @ author renchunxiao * * / public class ExecutorDemo {public static void main (String [] args) {Executor executor = new ThreadExecutor (); executor.execute (new Runnable () {@ Override public void run () {/ / do something}}); Executor executor2 = new SerialExecutor () Executor2.execute (new Runnable () {@ Override public void run () {/ / do something}}) }} / * create a thread to execute command * * @ author renchunxiao * * / class ThreadExecutor implements Executor {@ Override public void execute (Runnable command) {new Thread (command). Start ();} / * * Serial execution command * * @ author renchunxiao * * / class SerialExecutor implements Executor {@ Override public void execute (Runnable command) {command.run () }}

Thread pool

A thread pool is a resource pool for threads, which can be created through the static factory method in Executors.

NewFixedThreadPool . Create a fixed-length thread pool and create one thread at a time until the number of thread pools is reached, and the size of the thread pool will not change.

NewSingleThreadExecutor . A single thread pool.

NewCachedThreadPool . A pool of threads that varies according to the size of the task.

NewScheduledThreadPool . Create a fixed-length thread pool to execute tasks in a delayed or scheduled manner.

JVM does not exit until all non-daemon threads are terminated, so if Executor is not closed correctly, JVM cannot end.

To solve the lifecycle problem of executing services, there is a new interface ExecutorService that extends the Executor interface.

Public interface ExecutorService extends Executor {void shutdown (); List shutdownNow (); boolean isShutdown (); boolean isTerminated (); boolean awaitTermination (long timeout, TimeUnit unit) throws InterruptedException; Future submit (Callable task); Future submit (Runnable task, T result); Future submit (Runnable task); List invokeAll (Collection)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report