3

I have this thread:

                    t = new Thread() {
                    @Override
                    public void run() {
                        try {
                            while (!isInterrupted()) {
                                Thread.sleep(1);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        TimeCounter++;
                                        textview.setText("Your reaction time:"
                                                + TimeCounter + "MS");
                                    }
                                });
                            }
                        } catch (InterruptedException e) {
                        }
                    }
                };

                t.start();

I want to cancel it , I tried the t.interrupt(); but it didn't work, is there any other way?

David
  • 39
  • 4

3 Answers3

0

I had an issue related to this before. You might find this link useful as this is how I solved this problem. Also, as already mentioned, it is quite odd that you are setting your thread to sleep for 1 millisecond. Thread isn't removed properly

Community
  • 1
  • 1
Programmer
  • 459
  • 5
  • 20
  • I just wanted to update a textview every millisecond so I used thread and sleep for one millisec, is there other way? – David Aug 18 '14 at 16:27
  • Oh ok, I understand. Personally I would use something like a [CountDownTimer](http://developer.android.com/reference/android/os/CountDownTimer.html). It allows you to specifically state the interval as well. – Programmer Aug 18 '14 at 16:31
  • This may help you understand how to use it properly in your code.[How to make a countdowntimer](http://stackoverflow.com/questions/10032003/how-to-make-a-countdown-timer-in-android/10032406#10032406) – Programmer Aug 18 '14 at 16:35
  • I honestly think this would be a better solution than using a thread (although I don't know the exact context of your program). You could have the onTick() handle updating the TextView which would happen based on your interval. Also, I believe that the CountDownTimer runs on it's own type of thread (I could be mistaken). – Programmer Aug 18 '14 at 16:42
  • You are right but I need it to be for an unknown time so I can't use the CountDownTimer because he might finished, anyway, I solved it, thank you!\ – David Aug 18 '14 at 16:43
0

Your problem may be that it works properly but you have a lot of runonUiThread commands pending. Doing a runOnUiThread that frequently is NOT recommended, you're doing a lot of processing and inter-thread communication.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

Read this :

How do you kill a thread in Java?

and :

http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

Community
  • 1
  • 1
MilanNz
  • 1,323
  • 3
  • 12
  • 29