如何在Java中按顺序调用方法?
我正在用Java编写一个套接字应用程序。代码如下:如何在Java中按顺序调用方法?,java,multithreading,sockets,asynchronous,Java,Multithreading,Sockets,Asynchronous,我正在用Java编写一个套接字应用程序。代码如下: client.Send("Server is closing the connection!");//Send() method will be executed in another thread. client.Close(); 我希望Close()总是在Send()之后执行,以确保客户端在连接关闭之前收到消息。如何实现这一点 我是一名.NET程序员,所以我想使用wait-like await client.SendAsync("Serv
client.Send("Server is closing the connection!");//Send() method will be executed in another thread.
client.Close();
我希望Close()
总是在Send()
之后执行,以确保客户端在连接关闭之前收到消息。如何实现这一点
我是一名.NET程序员,所以我想使用wait-like
await client.SendAsync("Server is closing the connection!");//Send() method will be executed in another thread.
client.Close();
在C#中,如何在Java中获得相同的结果
---更新---
关于Send()
:
您可以在thread对象上使用join()方法等待发送操作完成,和/或可以像这样使用Observer模式
public interface TransferListener{
public void dataSent();
public void connectionError();
}
将实现TransferListener接口的实例传递给调用send方法的线程,如果操作成功,则使用“dataSent”方法通知侦听器,如果发生错误,则使用“connectionError”方法通知侦听器
------编辑-----
要发送其他线程,请执行以下操作:
final Socket client = ...; // it must be final to be used in a inner class
Thread t = new Thread( new Runnable(){
public void run(){
client.Send(...); //
}
};
t.start();
要阻止当前线程直到线程“t”完成,请执行以下操作:
t.join();
此外,如果您不想在发送完成之前阻塞以进行其他计算(例如,不冻结UI),您可以使用观察者模式(相当于C#中的委托),就像我解释的那样。send方法看起来如何?不相关,请在方法中使用
camel case
,不要以大写字母开头。@YCF\L已更新<代码>发送()在新线程中执行操作。
t.join();