如何将while
循环放入线程中?
public class Weather {
public static void main(String[] args) throws UnknownHostException, IOException {
String host = "rainmaker.wunderground.com";
int port = 3000;
int byteOfData;
{
try (Socket socket = new Socket(host, port);
InputStream inputStream = socket.getInputStream();
OutputStream ouputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
//also, a thread for reading from stdin
Thread remoteOutputStream = new Thread() {
@Override
public void run() {
//while loop should go here
// java.net.SocketException: Socket closed
//why does this error occur?
}
};
remoteOutputStream.start();
while ((byteOfData = inputStream.read()) != -1) { //put into thread
out.print((char) byteOfData);
}
}
}
}
}
当我将while
循环放入线程时,它只是抛出java.net.SocketException: Socket closed
,因为大概是因为try with resources works
. 但是,我不知道如何在这种尝试中使用线程。
因为会有多个线程,一个用于读取本地InputStream,一个用于远程OutputStream,似乎有必要将线程放入,try
反之亦然..?