简体   繁体   中英

Multi-client server use: which method better

Creating multi-client server use extends Thread or implements Runnable in Java.

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

Please read "implements Runnable" vs "extends Thread" in 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

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 )

Executors framework

I assume you meant “multi-threaded” where you wrote “multi client server”.

In modern Java we rarely manage threads manually. We now have the Executors framework to handle the details of juggling threads. So no need to extend 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. See the Executors class to produce an executor service.

You get back a Future object that can be checked for the task being done, cancelled, or still pending.

This has been addressed many times already on Stack Overflow. Search to learn more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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