0
thread = new Thread()
        {
            @Override
            public void run() {
                while(!requestedToExit)
                {
                    SystemClock.sleep(3000);
                    Log.d("debug", "in");
                }
            }
        };

So a button got an event, Each time I click on it it's start the thread (if the previous thread is not alive).

So I tried use thread.start() but it throw thread already started. I tried .run(), nothing happens, I also tried each time I click on the button, and it's possible to run it again, create a new thread and start it : nothing.

Some ideas ?


Using Runnable :

   r= new Runnable(){

            public void run() {
                while(!requestedToExit)
                {
                    Log.d("debug", "in");
                    SystemClock.sleep(3000);

                }
            }
        };

Then I use in my listener :

thread = new Thread(injection);
thread.start();

But I only see the debug the first time, he never enter into it after.

Thanks in advance

1 Answer 1

5

From the JavaDoc -

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

Instead, use java.lang.Runnable and create a new thread to run it when you have to.

What you need to do is:

Runnable r = new Runnable() {
    public void run() {
        ....
    }
};

Then, when you want to start it:

Thread t = new Thread(r);
t.start();

You need to always create a new thread to run that one runnable.

3
  • I edited my first post. Thanks in advance PS : I wanted to use the function from Thread and Runnable too, .isAlive is pretty useful for me.
    – Shinao
    Apr 26, 2012 at 12:02
  • I re-edited my first post. I don't use Thread t = new Thread(r) but t = new Thread(r) because I define it at the beginning private Thread thread = new Thread();, else I cannot know if my thread isAlive() the first time, but I think it's not the problem because I use new Thread(). Thanks for your help
    – Shinao
    Apr 26, 2012 at 13:08
  • God I'm retarded, forgot to set requestedToExit at false... Thanks
    – Shinao
    Apr 26, 2012 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.