线程中有循环,如何能够安全中止线程
最近做一个awt的udp小程序
服务器端要实时检测端口
需要一个循环实现
不知道在线程中如何实现安全中止线程
用thread.stop()界面会有问题
简单代码如下:
public class udp_thread extends Thread
{
private int port;
private int buffer_size;
private JTextArea mem_message;
public udp_thread(int port, int buffer_size, JTextArea mem_message)
{
this.port = port;
this.buffer_size = buffer_size;
this.mem_message = mem_message;
}
public void run()
{
byte[] buffer = new byte[buffer_size];
try
{
DatagramSocket server = new DatagramSocket(port);
while(true)
{
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
server.receive(packet);
if (packet.getLength() <= 0)
continue;
this.respond(packet);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
public void respond(DatagramPacket packet)
{
byte[] buffer = new byte[packet.getLength()];
System.arraycopy(packet.getData(), 0, buffer, 0, packet.getLength());
try
{
String str = new String(buffer, "8859_1 ");