0

Hi I'm trying to stop a thread while running I know the thread should cooperate so it can be stopped I used a boolean variable but the thread keeps running. is there any way to stop a thread while it's running? Or can I start and stop a thread with the same button?

boolean boolean_variable  = true;

     Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                while (boolean_variable) {
                    for (int i = 0; i < 100; i++) {
                        System.out.println("thread running " + i);
                        try {
                            Thread.sleep(400);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

//start the thread
buttonOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                thread.start();
            }
        });

//stop the thread
buttonTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean_variable = false;
            }
        });
Behzad
  • 1
  • 3
  • 1
    Firstly, `boolean_variable` would need to be `volatile` to ensure visibility of updates to its value. – Andy Turner Dec 09 '22 at 09:29
  • 1
    Secondly, you're checking the `boolean_variable` outside the loop, so it will only be checked once the 100 `sleep`s are all done. – Andy Turner Dec 09 '22 at 09:30
  • Thirdly, you're not interrupting the thread; but if you did, you are catching and swallowing the interruption, so you would just go straight back to sleeping again. – Andy Turner Dec 09 '22 at 09:31
  • yeah, thanks, I put the boolean_variable inside the loop and it worked. – Behzad Dec 09 '22 at 09:37
  • Andy Turner said, "you're not interrupting the thread." But that's probably not a problem for you in _this_ case. Calling `thread.interrupt()` from the GUI would cause the `sleep()` call to throw the exception, and that would give your thread a chance to _promptly_ check the `boolean_variable` instead of waiting for the sleep to finish naturally. But since the duration of your sleep call is less than half a second, waiting for it to finish might not be a problem for you. If you change it to sleep for longer periods of time, _then_ you might want buttonTwo to interrupt the thread. – Solomon Slow Dec 09 '22 at 12:52

0 Answers0