In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces how to achieve Java 5.0multithreaded programming, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
Brief introduction
This paper will implement a network server model, once a client connects to the server, a new thread is started to serve the connection, and the service content is to send some character information to the client. A typical network server model is as follows:
1. Establish a listening port.
two。 Find a new connection, accept the connection, start the thread, execute the service thread. 3. When the service is complete, close the thread.
This model works well in most cases, but when the user request needs to be processed frequently and the service required for each request is short, the system will spend a lot of time on thread creation and destruction. Java 5's thread pool overcomes these shortcomings. Through reusing threads to perform multiple tasks, the overhead of frequent thread creation and destruction is avoided, and the performance of the server is greatly improved. Therefore, the network server model of this article will be as follows:
1. Establish a listening port and create a thread pool.
two。 A new connection is found and a thread pool is used to perform the service task.
3. When the service is complete, release the thread to the thread pool.
The following details describe how to implement the server using the API provided by the concurrent package of Java 5.
Initialization
Initialization includes the creation of thread pools and initialization of listening ports. The thread pool can be created by calling the static method newChahedThreadPool or newFixedThreadPool in the java.util.concurrent.Executors class, or by creating a new java.util.concurrent.ThreadPoolExecutor instance to perform the task. Here we use the newFixedThreadPool method to establish the thread pool.
ExecutorService pool = Executors.newFixedThreadPool (10)
Indicates that a new thread pool has been created, in which there are 10 threads serving the task queue.
Use the ServerSocket object to initialize the listening port.
Private static final int PORT = 19527th serverListensocket = new ServerSocket (PORT); serverListenSocket.setReuseAddress (true); serverListenSocket.setReuseAddress (true)
Service new connection
When a new connection is established and accept returns, the service task is submitted to the thread pool for execution.
While (true) {Socket socket = serverListenSocket.accept (); pool.execute (new ServiceThread (socket));}
Thread pool objects are used here to execute threads, reducing the overhead of each thread creation and destruction. After the task is executed, the thread is released to the thread pool.
Service task
The service thread ServiceThread maintains a count to record the number of times the service thread is invoked. Each time a service task is called, the value of count increments itself by 1, so ServiceThread provides a method for increaseCount and getCount to increase the count value by 1 and get the count value, respectively. Because there may be multiple threads competing to access count at the same time, we need a locking mechanism, and before Java 5, we could only use synchronized to lock. ReentrantLock, a reentrant lock with more granular performance, has been introduced in Java 5. We use ReentrantLock to keep the code thread safe. Here is the specific code:
Private static ReentrantLock lock = new ReentrantLock (); private static int count = 0; private int getCount () {int ret = 0; try {lock.lock (); ret = count;} finally {lock.unlock ();} return ret;} private void increaseCount () {try {lock.lock (); + + count;} finally {lock.unlock ();}}
The service thread starts to print a welcome message to the client
IncreaseCount (); int curCount = getCount (); helloString = "hello, id =" + curCount+ "\ r\ n"; dos = new DataOutputStream (connectedSocket.getOutputStream ()); dos.write (helloString.getBytes ())
Then use the submit method of ExecutorService to submit a Callable task and return a reference to the Future interface. This is very effective for time-consuming tasks. After the submit task, you can continue to execute the following code, and then you can use Future's get method to get the results where appropriate. If the method has been executed by this time, you don't have to wait to get the results. If you are still executing, you can wait until the result is finished.
ExecutorService executor = Executors.newSingleThreadExecutor (); Future future = executor.submit (new TimeConsumingTask ()); dos.write ("let's do soemthing other" .getBytes ()); String result = future.get (); dos.write (result.getBytes ()); / / where TimeConsumingTask implements the Callable interface class TimeConsumingTask implements Callable {public String call () throws Exception {System.out.println ("It's a time-consuming task, you'd better retrieve your result in the furture") Return "ok, here's the result: It takes me lots of time to produce this result";}}
Another new feature of Java 5 generics is used here, which declares TimeConsumingTask using String as a type parameter. The call function of the Callable interface must be implemented, which is similar to the run function in Runnable, where the code to be executed is written in the call function, and the return value type is equivalent to the type value passed in the class declaration. In this program, we submit a Callable task, and the program does not block, but continues to execute dos.write ("let's do soemthing other" .getBytes ()); when the program executes to String result = future.get (), if the call function has finished executing, it gets the return value, and if it is still executing, it waits for it to finish.
Thank you for reading this article carefully. I hope the article "how to realize Java 5.0multithreaded programming" shared by the editor will be helpful to everyone. At the same time, I also hope you can support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.