-2

I have thread in my android app which finish its task but still it is not exit , when I run it again I got error that thread is already alive

my thread

    Thread mythreads = new Thread()
    {
        @Override
        public void run() {
       // do some work

       // exit point      
}
};

so please how can I stop this even thread finish it code execution , but when I try to run it again it give me error

java.lang.IllegalThreadStateException: Thread already started

I try to stop with it with my threadkill function code but no success

public void killthread(Thread tname){
    try {
        if (tname.isAlive()) {
            Log.d("tag1","Thread is Alive");
            tname.interrupt();
            tname = null;
        }
    }catch (Exception e){
        e.printStackTrace();
    }
}
Elemental
  • 7,365
  • 2
  • 28
  • 33
  • perhaps you should understand when a thread is considered [alive](http://stackoverflow.com/questions/17293304/when-is-a-java-thread-alive) – chancea Jul 15 '14 at 19:30

1 Answers1

1

Thread objects are only meant to be started once. If you need to stop/interrupt a Thread, and then want to start it again, you should create a new instance, and call start() on it:

thread.interrupt();
thread = new YourThreadSubclass();
thread.start();

In your case you are doing Thread mythreads = new Thread() so it shouldn't be a problem at all unless you are explicitly trying to stop it before completion of the excecution.

Creating Anonymous Thread

new Thread()
{
    public void run() {
        //Your code
    }
}.start();
CodeWarrior
  • 5,026
  • 6
  • 30
  • 46
  • so do you not think that it will create memory issue because after specific time i want to start my thread , and by using your method i have to create every time new object ....... i mean it will use more memory ??? – user134929 Jul 15 '14 at 19:28
  • @user134929 it shouldn't, once you create a new instance of your thread it will mark the old one for garbage collection (unless you have an implicit reference to your context). – zgc7009 Jul 15 '14 at 19:32
  • can you tell me how i can create new instance of my thread , i mean i start my thread mythreads.start(); it completed and still alive so how to create new instance ?? please help – user134929 Jul 15 '14 at 19:45
  • @user134929 Create an Anonymous thread and you won't face any issues. I'll update it in my code. – CodeWarrior Jul 15 '14 at 19:50