如何將while
循環放入線程?如何將一個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
的。但是,我不知道如何使用這種嘗試的線程。
因爲將多個線程,一個用於讀取遠程的OutputStream當地的InputStream和一個,似乎有必要把線程注入try
,而不是相反..?
doh,我一如既往地提出錯誤的問題。這更有意義,你的方式:)出於好奇,假設這是解決方案,但爲什麼它不起作用? – Thufir
因爲'inputStream'和'byteOfData'在一個單獨的線程中 –
嗯,我最終會變得更糟糕(到目前爲止)。另外,我需要一個線程來讀取一個打開的流,一個線程可以寫入一個打開的流。 – Thufir