Click here to Skip to main content
15,881,730 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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..
Java
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!");
            }
        }
    }

}
Posted

1 solution

You can interrupt a thread with the interrupt() method.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900