多个线程中的一个如果调用了socket.close()方法,其他线程在进行读/写时会出现socket close异常,例如:
java.net.SocketException: socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at java.net.SocketInputStream.read(SocketInputStream.java:90)
at server. UserListener .run(UserListener.java:36)
at java.lang.Thread.run(Thread.java:662)
下面是对应的代码,父线程在执行完任务后sock.close()关闭了socket,导致south线程中uin(sock的InputStream)运行read()方法时出现socket close异常:
父线程:
uin = sock.getInputStream(); uout = sock.getOutputStream(); Runnable south = new UserListener (uin, nos); new Thread(south, "south").start(); ... sock.close();
south线程:
public class UserListener implements Runnable { @Override public void run() { ... recv = uin.read(buf); //异常抛出点 ...