What is the best way to kill a thread in a Timer?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • phpuser123
    New Member
    • Dec 2009
    • 108

    What is the best way to kill a thread in a Timer?

    What is the best way to kill a thread in a timer such that every time the timer runs, it kills the previous thread before starting a new one?

    Code:
    public class MapTimer extends TimerTask{
    
    public void run() {
    
    
            try {
    
                connected = startConnection();
                sendMessage(this.message);
                System.out.println("Sending message111 ..."+this.message);
                serverquerystring=receiveMessage();
              
                thread = new Thread() {
                public void run() {
                        try {
                             System.out.println("In run..");
    
                            checkquery(serverquerystring);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                }
        };
        thread.start(); // write post-action user code here
        }
    
    
              catch(Exception e){
                System.out.println("Error "+e);
           }
    
    }
    }
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    Keep a reference to the currently active thread (some Thread variable) when your timer executes, tell the thread to stop. (See tutorials on best practices for exiting the thread) You can then do a .Join() (with a timeout so that you can call .Abort() if need be)
    Then start your new thread when the previous one exits?

    Comment

    Working...