I have this code:
public void post(String message) {
output.close();
final String mess = message;
(new Thread() {
public void run() {
while (true) {
try {
output.println(mess);
System.out.println("The following message was successfully sent:");
System.out.println(mess);
break;
} catch (NullPointerException e) {
try {Thread.sleep(1000);} catch (InterruptedException ie) {}
}
}
}
}).start();
}
正如您所看到的,我在代码开头关闭了套接字,然后尝试将一些信息发送到另一台计算机。程序会写入“以下消息已成功发送”。这意味着未抛出NullPointerException异常。
那么,如果尝试使用已关闭的套接字输出流,Java是否不会抛出任何异常?有没有办法检查套接字是关闭还是打开?
添加:
我以以下方式初始化套接字:
clientSideSocket = new Socket(hostname,port);
PrintWriter out = new PrintWriter(clientSideSocket.getOutputStream(), true);
browser.output = out;
output
成员变量声明为volatile
会发生什么? - Ash