Several things at once (Themes?)

All,

Which is a really simple way to have the program do several things at once, even if the computer does not necessarily have several “cores”. Can I do this by creating multiple threads?

My goal is to have two computers on the network (via Sockets) to respond to each other's requests, while my program will at the same time be able to control the user interface. I want the server to potentially handle more than one client at a time.

I understand that communication is done using BufferedReader.readLine () and PrintWriter.println (). My problem is that I want the server to expect several readLine () requests, as well as do other things. How can I handle this?

Many thanks,

Jonathan

+4
source share
5 answers

Yes, you can do this by having multiple threads inside your Java program.

As mechanisms in Java become quite complex when you do this, check out the appropriate section in the Java tutorial:

http://java.sun.com/docs/books/tutorial/essential/concurrency/

+1
source

Take a look at this page: http://www.ashishmyles.com/tutorials/tcpchat/index.html - this gives a good description of the threads, user interface details, etc., and gives an example chat in which they combine them together.

Also consider using Apache MINA . It is quite lightweight, does not rely on any external libraries (except slf4j) and simplifies the collection of data from sockets without the need to go in a loop, and also does not block quite a lot (or blocks when you need it). So, you have a class that implements IoHandler, and then you register this using an acceptor or another Mina join class. He then notifies you of the receipt of packages. It processes all the backends familiar to you (for example, manually creates several threads for clients, and then manages them). A.

It also has codec support where you can convert sent and received messages. So, say you want to receive Java objects at both ends of your connection - this will do the conversion for you. You may also want to fasten them to make it more effective? You can also write this by adding it to the chain under the object codec.

+1
source

Yes, just create multiple threads. They will work simultaneously, regardless of whether the processor has multiple cores. (With one core, the OS simply pauses the execution of the current thread at certain points and starts another thread for a while, therefore, in fact, several work simultaneously at the same time).

Here is a good concurrency tutorial: http://java.sun.com/docs/books/tutorial/essential/concurrency/

+1
source

The standard Java tutorial for Sockets is a good start. I wrote the exact program that you describe using this as a base. The last point on the Multi-Client Support page describes how threads are implemented.

http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html

+1
source

Can I do this by creating multiple threads?

What is a really simple way, a program does more than one at a time, even if a computer doesn’t necessarily have several “cores”. Can I do this by creating a few theme?


If you have 1 single-core processor, then only the “official” only one task can be completed. Because your computer s processor is so fast and executes so many instructions per second, it creates the illusion that your computer performs several tasks at the same time, while each small unit performs only one task. You can create this illusion in Java by creating threads that are planned by your operating system in a short period of time.

My advice is to take a look at the java.util.concurrent package because it contains many useful tools for playing with streams much easier (in those days when this package was not there, it was much more complicated). For example, I like to use

ExecutorService es = Executors.newCachedThreadPool();

to create a thread pool that I can submit jobs at once. Then, when I have a task that I like to run, I call

es.execute(runnable);

where runnable is as follows:

 Runnable runnable = new Runnable() { public void run() { // code to run. } }; 

For example, let's say you run the following code:

 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mytests; import java.util.Date; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * * @author alfred */ public class Main { /** * @param args the command line arguments * @throws Exception */ public static void main(String[] args) throws Exception { // TODO code application logic here final CountDownLatch latch = new CountDownLatch(2); final long start = System.nanoTime(); ExecutorService es = Executors.newCachedThreadPool(); Runnable runnable = new Runnable() { public void run() { sleep(1); System.out.println(new Date()); latch.countDown(); } }; es.submit(runnable); es.submit(runnable); latch.await(); // waits only latch.countDown() has been called 2 times. // 1 nanoseconds is equal to 1/1000000000 of a second. long total = (System.nanoTime() - start) / 1000000; System.out.println("total time: " + total); es.shutdown(); } public static void sleep(int i) { try { Thread.sleep(i * 1000); } catch (InterruptedException ie) {} } } 

The result will look like

 run: Fri Apr 02 03:34:14 CEST 2010 Fri Apr 02 03:34:14 CEST 2010 total time: 1055 BUILD SUCCESSFUL (total time: 1 second) 

But I had 2 tasks, each of which completed at least 1 second (due to sleep 1 second). If I completed these 2 tasks sequentially, it would take at least 2 seconds, but since I used threads, it took only 1 second. This is what you wanted and it is easy to accomplish with the java.util.concurrent package.

I want the server to potentially handle more than one client at a time.

My goal is to have two computers connected to the network (via Sockets) respond to each other's requests, while my program will at the same time be able to control the user interface. I want a server that can potentially handle more than one client at a time well.


I would advise you to take a look at the Netty framework (MINA, which is also developed by the creator of MINA, but Netty is better (more development), in my opinion) .:

The Netty project is an attempt to provide asynchronous event management network application infrastructure and tools for rapid development supported by high performance and high scalability protocol servers and amp; customers.

He will do all the hard work for you. When I read the user manual, I was completely amazed at netty. Netty uses nio , which for highly competitive servers is a new way to do IOs that scale much better. As I said before this frame does all the heavy lifting for you

My problem is that I want the server to wait for several readLine () requests and also do other things

I understand that communication is done using BufferedReader.readLine () and PrintWriter.println (). My problem is that I want the server to wait on several readLine () requests and also do other things. How do I handle this?

Again, when you look at the netty + user manual examples, you will find out that it does all the heavy lifting for you in an efficient way. You will only need to specify some callbacks to receive data from clients.


Hope this answered all your questions. Otherwise, I would advise you to leave a comment so that I try to explain it better.

+1
source

Source: https://habr.com/ru/post/1305813/


All Articles