[英]Java : How do I call a method in a different class that extends Thread and is a part of a Thread Array from my main class?
I have a simple main class which listens on a socket, and adds (networked) clients to an array of Threads as they join in ( like a server listening for new chat clients , and adding each client as a thread , and maintaining the list of threads as an array). 我有一个简单的主类,它侦听套接字,并在它们加入时将(网络的)客户端添加到线程数组中(例如服务器侦听新的聊天客户端,并将每个客户端添加为线程,并维护线程列表)。线程作为数组)。
Other things are working, these are the code lines where the server listens and adds a new client to an array of threads called thdRunningClientsPool[] 其他事情正在起作用,这些是服务器侦听并向名为thdRunningClientsPool []的线程数组添加新客户端的代码行。
//add a new ClientHandler type object( ClientHandler class extends Thread) to my Thread Array
public void run() {
............
thdRunningClientsPool[intRunningClients]= new
Thread( new ClientHandler(clientSocket));
thdRunningClientsPool[intRunningClients].start();
Now, The ClientHandler class has a method void SendMessage(string Message) 现在,ClientHandler类具有方法void SendMessage(string Message)
How do I send a message using this SendMessage method after a new client is added? 添加新客户端后,如何使用此SendMessage方法发送消息? When I use this
当我用这个
thdRunningClientsPool[intRunningClients].SendMessage("hi");
The SendMessage method is not found. 找不到SendMessage方法。 Java is treating thdRunningClientsPool(intRunningClients) as a thread, not as a object of ClientHandler class and so I can't acces my SendMessage method.
Java将thdRunningClientsPool(intRunningClients)视为线程,而不是ClientHandler类的对象,因此我无法访问我的SendMessage方法。
How can I fix this? 我怎样才能解决这个问题? Any advice greatly appreciated :) THxxx
任何建议,不胜感激:) THxxx
First, general advice: use implements Runnable
instead of extends Thread
. 首先,一般建议:使用
implements Runnable
而不是extends Thread
。 Will save you a lot of headaches down the road. 将为您免去很多麻烦。
As for your question, you can't call sendMessage
on the Thread
instance that was passed your instance as an argument. 至于您的问题,您不能在作为参数传递给您的实例的
Thread
实例上调用sendMessage
。 You must change the code to hold references to your ClientHandler
s; 您必须更改代码以保存对
ClientHandler
的引用; you don't really need the array of outer Thread
instances. 您实际上并不需要外部
Thread
实例的数组。 Just start them and let go of them. 只需启动它们,然后放开它们。
You should also reconsider your choice to start all those threads on your own, this is usually a bad idea because it wastes system resources. 您还应该重新考虑自己启动所有这些线程的选择,这通常是一个坏主意,因为这会浪费系统资源。 However, redesigning that aspect of your code is beyond the scope of your question.
但是,重新设计代码的这一方面超出了您的问题范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.