简体   繁体   English

多客户端服务器使用:哪种方法更好

[英]Multi-client server use: which method better

Creating multi-client server use extends Thread or implements Runnable in Java.创建多客户端服务器使用扩展Thread或实现 Java 中的Runnable

Using使用

public class Receiver implements Runnable {

or或者

public class Receiver extends Thread {

Which one is better for my code?哪一个更适合我的代码?

It is always better to Implement Runnable, In case you are using Runnable u can execute it with a thread or threadpool实现 Runnable 总是更好,如果您使用 Runnable,您可以使用线程或线程池执行它

Please read "implements Runnable" vs "extends Thread" in Java请阅读Java 中的“实现可运行”与“扩展线程”

for more details更多细节

Here are some links that can help you find your answer这里有一些链接可以帮助您找到答案

https://www.geeksforgeeks.org/implement-runnable-vs-extend-thread-in-java/ "implements Runnable" vs "extends Thread" in Java https://www.geeksforgeeks.org/implement-runnable-vs-extend-thread-in-java/ Java 中的“实现可运行”与“扩展线程”

In your specific case I think (guess) that your Receiver class is not a Thread (by means of OOP) but should work in a Thread or Perform Multi-threaded which means it should not extends Thread (there is no is-a relationship between Receiver and Thread )在您的特定情况下,我认为(猜测)您的接收器class不是线程(通过 OOP),但应该在线程中工作执行多线程,这意味着它不应该扩展线程(之间没有is-a关系接收器线程

Executors framework执行者框架

I assume you meant “multi-threaded” where you wrote “multi client server”.我假设您的意思是“多线程”,您在其中编写了“多客户端服务器”。

In modern Java we rarely manage threads manually.在现代 Java 中,我们很少手动管理线程。 We now have the Executors framework to handle the details of juggling threads.我们现在有了 Executors 框架来处理杂耍线程的细节。 So no need to extend Thread .所以不需要扩展Thread

Tasks to be run on a background thread should be written as either a Runnable or a Callable , and then submitted to an executor service.要在后台线程上运行的任务应编写为RunnableCallable ,然后提交给执行器服务。 See the Executors class to produce an executor service.请参阅Executors class 以生成执行器服务。

You get back a Future object that can be checked for the task being done, cancelled, or still pending.您将返回一个Future object,可以检查该任务是否已完成、已取消或仍待处理。

This has been addressed many times already on Stack Overflow. Stack Overflow 上已经多次解决了这个问题。 Search to learn more.搜索以了解更多信息。

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

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