gpt4 book ai didi

java - 如何使用 try 和资源将 while 循环放入线程中?

转载 作者:行者123 更新时间:2023-12-01 18:39:26 27 4
gpt4 key购买 nike

如何将 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 因为,大概是因为如何尝试使用资源有效。但是,我不知道如何使用线程进行这种尝试。

因为多个线程,一个用于读取本地InputStream,一个用于远程OutputStream,所以似乎有必要将线程放入try而不是相反反之亦然..?

最佳答案

将整个 try with resources 语句放入线程中

final String host = "rainmaker.wunderground.com";
final int port = 3000;

{
Thread remote = new Thread()
{
@Override public void run()
{
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)))
{
int byteOfData;

while ((byteOfData = inputStream.read()) != -1)
{ //put into thread
out.print((char)byteOfData);
}
}
}
};
remote.start();

关于java - 如何使用 try 和资源将 while 循环放入线程中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20539837/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com