0

I made thread that send String back to main thread periodically. and I put this thread on some function.

When I press some button, than function will be called and do the work.

The problem is when I press that button twice.

That two threads are sending their String to main thread. (They do the exactly same thing, but different string.)

But I don't need the first thread when thread started again.

Is their any way to kill the first thread?

here's the code.

private void speller_textbox(final String string){
    final int strlen = string.length();
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            int cursor= 0;
            while(cursor != strlen){
                try{
                    Message message = Message.obtain();
                    message.obj = string.subSequence(0,cursor);
                    txt_handler.sendMessage(message);
                    cursor++;
                    Thread.sleep(100);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    });
    thread.start();
}

txt_handler is on the main thread.

  • Is the question how to determine if there is a thread that needs to be killed, or how to kill it, or both? – Scott Hunter Jul 11 '16 at 14:15
  • well, both. I need to determine and kill it. – Gyunghwan Oh Jul 11 '16 at 14:21
  • 2
    You don't really "kill" threads. There are methods like `stop` and `destroy` on `Thread`, but they are strongly deprecated. All you can do is to interrupt a running thread, and implement it in such a way that it can check for the interruption and stop as soon as possible. – Andy Turner Jul 11 '16 at 14:22
  • Since you wrote the code to create the thread, that same code should be able to do something so that it can tell that it did so later. `speller_textbox` is part of some object, right? – Scott Hunter Jul 11 '16 at 14:24
  • @ScottHunter / Yes. – Gyunghwan Oh Jul 11 '16 at 14:41

1 Answers1

-1

First replace your working thread from method. Than:

private Thread workingThread;

//.....

private void speller_textbox(final String string){

    if (workingThread != null && workingThread.isAlive()) {
        workingThread.interrupt();
    }

    final int strlen = string.length();
    workingThread = new Thread(new Runnable() {
        @Override
        public void run() {
            int cursor= 0;
            while(cursor != strlen){
                try{
                    Message message = Message.obtain();
                    message.obj = string.subSequence(0,cursor);
                    txt_handler.sendMessage(message);
                    cursor++;
                    Thread.sleep(100);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    });
    thread.start();
}
GensaGames
  • 5,538
  • 4
  • 24
  • 53