我是编程新手。我的单身汉项目只需要一个程序。
我在程序中运行一个线程时遇到问题,该线程使用缓冲读卡器来保存来自互联网流的一些数据。当我第一次运行线程时,一切都运行得很好但是当我完成它并运行一个新线程时,线程似乎正在工作,但是缓冲读取器部分的循环在某种程度上不起作用。你能救我吗?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextField;
volatile boolean stopRequested = false;
private Socket socket = null;
private BufferedReader in = null;
public void runMe() {
stopRequested = false;
Thread vypocet = new Thread(mytask);
vypocet.start();
}
public void stopMe() {
stopRequested = true;
}
public Runnable mytask = () -> {
try {
socket = new Socket(Gui.iP.getText(), Integer.parseInt(Gui.port.getText()));
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection");
System.exit(1);
}
try {
for (String line = in.readLine(); stopRequested != true; line = in.readLine()) {
//some calculation I need
}
catch (IOException ex1) {
Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex1);
System.err.println("Error in loading receiver's data. Please turn the program off and on again.");
System.exit(1);
}
System.out.println("End of the calculation");
};