Java 线程:自动终止
Java Threads: Automatic Termination
我想知道正在创建的这个线程(参考代码片段)是否会在完成其工作后在垃圾回收中自动终止。
我正在创建一个基本的聊天程序来学习如何使用套接字、创建客户端和创建服务器。我很快发现,如果我希望能够从客户端发送和接收消息,而不是仅在发送时更新,我需要对客户端进行多线程处理。一个线程用于接收消息和更新我的 GUI,一个用于发送。我有以下代码片段,只要我的聊天室 GUI 上的按钮触发 ActionEvent
,就会调用它。一旦我注意到每次发送消息时,都会创建一个顺序更高的线程,我就开始担心了。我担心以前的线程没有被正确删除并且还在内存中,因此数字更高。
代码:
public void send(String message)
{
//Create a new thread so that the client can receive messages while it's sending them.
Thread thread = new Thread(new Runnable()
{
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run()
{
try
{
System.out.println("Writing chars");
output.writeUTF(message);
} catch (IOException exception)
{
System.out.println("Error attempting to write: " + message + " to the server.");
exception.printStackTrace();
}
}
});
thread.start();
}
在您的 run()
方法 returns 之后,Thread
将终止并最终被垃圾收集。您会看到递增的 ID 号,因为您正在为每个此类操作启动新线程 - 这不是建议的体系结构,但确实有效。
我想知道正在创建的这个线程(参考代码片段)是否会在完成其工作后在垃圾回收中自动终止。
我正在创建一个基本的聊天程序来学习如何使用套接字、创建客户端和创建服务器。我很快发现,如果我希望能够从客户端发送和接收消息,而不是仅在发送时更新,我需要对客户端进行多线程处理。一个线程用于接收消息和更新我的 GUI,一个用于发送。我有以下代码片段,只要我的聊天室 GUI 上的按钮触发 ActionEvent
,就会调用它。一旦我注意到每次发送消息时,都会创建一个顺序更高的线程,我就开始担心了。我担心以前的线程没有被正确删除并且还在内存中,因此数字更高。
代码:
public void send(String message)
{
//Create a new thread so that the client can receive messages while it's sending them.
Thread thread = new Thread(new Runnable()
{
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run()
{
try
{
System.out.println("Writing chars");
output.writeUTF(message);
} catch (IOException exception)
{
System.out.println("Error attempting to write: " + message + " to the server.");
exception.printStackTrace();
}
}
});
thread.start();
}
在您的 run()
方法 returns 之后,Thread
将终止并最终被垃圾收集。您会看到递增的 ID 号,因为您正在为每个此类操作启动新线程 - 这不是建议的体系结构,但确实有效。