简体   繁体   English

Java处理多个客户端-多线程吗?

[英]Java handling multiple clients - multithreading?

I got really interested into making an application that could accept & handle I/O out of multiple connected clients. 我对制作一个可以接受并处理来自多个连接客户端的I / O的应用程序非常感兴趣。

I've been told that I need to use two threads for this, for the performance. 有人告诉我,为此需要使用两个线程。

Thread-1 线程1

Accepting connections 接受连接

Thread-2 线程2

Handling clients I/O and response 处理客户端I / O和响应

I've took a look at what is a thread, I did use it, but I am not really sure how can I split my program (Don't have one, but just saying) into two threads. 我看了一下什么是线程,我确实使用了它,但是我不确定如何将程序(没有一个,只是说)分成两个线程。

How can I do that? 我怎样才能做到这一点?

One thread of these should have it's own class? 其中一个线程应该具有自己的类? I have no idea of a good design I can apply for this so I can understand it better. 我不知道有一个好的设计可以申请,所以我可以更好地理解。

How can I do this? 我怎样才能做到这一点? can you show me a little example? 你能给我举个例子吗?

Here's an example with a complete tutorial that I hope will be helpful. 这是一个带有完整教程的示例 ,希望对您有所帮助。 Note how you have one thread (the main one, right from the start) and everytime a connection is received, a new thread of the type KKMultiServerThread is spawn. 请注意,您如何拥有一个线程(主线程从头开始),并且每次接收到连接时,都会产生一个KKMultiServerThread类型的新线程。

Once you are familiar with this, consider using a Thread Pool rather than creation a new thread only when the connection starts. 熟悉此方法后,请考虑使用线程池,而不是仅在连接启动时才创建新线程。

Enjoy Java! 享受Java!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM