因此,我的服務器應用程序導致大量CPU使用率平均約95%。我認爲原因是它不斷產生新的線程,但沒有關閉它。我想如何在發生這種情況時關閉一個線程:刷新頁面,註銷,瀏覽器關閉。如何關閉多線程環境中的線程java
我的代碼或多或少像這樣的服務器部分。
ThreadedEchoServer.java
public class ThreadedEchoServer {
// using port 2000
static final int PORT = 2000;
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket socket = null;
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
new EchoThread(socket).start();
}
}
}
EchoThread.java
/*
Class for java server to accept incoming stream
and create a new thread to save log file data in server
*/
public class EchoThread extends Thread {
protected Socket socket;
public EchoThread(Socket clientSocket) {
this.socket = clientSocket;
}
public void run() {
/*Create a File*/
int i = 1;
try {
File directory = new File("F:/temp/tmplog/" + getDate());
if(!directory.exists()) {
directory.mkdir();
}
String fileName = "F:/temp/tmplog/" + getDate() + "/" + getDateTime() + ".txt";
File file = new File(fileName);
//Double Make Sure it create the file
while(file.exists()) {
file = new File(fileName + "." + i);
i++;
}
FileOutputStream fis = new FileOutputStream(file, true);
PrintStream out = new PrintStream(fis);
System.setOut(out);
while (true) {
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "US-ASCII"));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException exception) {
// Just handle next request.
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ignored) {
}
}
fis.close();
}
}
} catch (IOException ignored) {
}
}
此服務器應用程序basicly將打開一個新的和寫的每一個線程/客戶端的日誌文件。我認爲問題是我使用後沒有關閉線程。這就是爲什麼它只是產卵新的線程..任何幫助?
你可以把'println',看它是否離開這個循環:'而(file.exists())...'?還有另一個在'run'方法末尾看看線程是否退出? – Tudor
當然 - 調試EchoThread並找出客戶端關閉連接時會發生什麼。 'catch(IOException異常)'是否發生?如果是這樣,你在那裏做什麼?是否應該返回以便finally可以執行,關閉套接字並退出線程? –
@MartinJames我不確定的部分是線程是否會在((line = br.readLine())!= null){}時退出,因爲它會一直等待新的流。我想知道如果用戶刷新頁面或關閉瀏覽器會發生什麼?它會自動退出該循環,或者如何確保它退出循環。 – Harts