有关用于简单聊天服务器应用程序的线程和Swing的问题 [英] Question regarding Threads and Swing for simple chat server application

查看:93
本文介绍了有关用于简单聊天服务器应用程序的线程和Swing的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以根据布尔变量立即停止线程.在我的应用程序中,ReceiveMessage在while循环while(isRunning)中运行,但是布尔变量由windowClosing事件修改.我希望线程在关闭窗口时立即停止.

Is there a way to immediately stop a thread depending on a boolean variable. In my application, the ReceiveMessage runs in a while loop while(isRunning), but the boolean variable is modified by the windowClosing event. I want the thread to stop immediately when the window is closed..

public class ChatWindow extends WindowAdapter implements ActionListener {
..............
..............
    public void windowClosing(WindowEvent w){
		try{
			
			dos.flush();
                        frame.dispose();
                        isRunning =false;
			
                        //t1.stop();
			}catch(Exception oe){}
		}
}

class ReceiveMessage implements Runnable
{
..................
..................
    public void run()
    {
        
        while(ChatWindow.isRunning)
        {  try
            {
                while(true)
                {
                String str = dislocal.readUTF();
                chatmodel.addElement(chatwith+":> "+str);
                }
            }
            catch(Exception e)
            {
                System.out.println("Error receiving message!");
            }
        }
    }

}

推荐答案

您可以使用interrupt()方法中断线程.
You can interrupt a thread with the interrupt() method.


这篇关于有关用于简单聊天服务器应用程序的线程和Swing的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆