Gracefully stopping a java thread

0 votes

How do I stop a thread in Java. I created it, but it is taking too much of time to execute. Any suggestion will be appreciated.

Aug 21, 2018 in Java by 93.lynn
• 1,600 points
1,371 views

1 answer to this question.

0 votes

The preferable way will be to use a run() of the Thread and guard it by a boolean variable and set it to true from the outside when you want to stop it, something like:

class MyThread extends Thread
{
  volatile boolean finished = false;

  public void stopMe()
  {
    finished = true;
  }

  public void run()
  {
    while (!finished)
    {
      //your code
    }
  }
}
answered Aug 21, 2018 by anto.trigg4
• 3,440 points

Related Questions In Java

0 votes
1 answer

How to kill a thread in Java?

You can use a shared variable as ...READ MORE

answered Jun 6, 2018 in Java by Akrati
• 3,190 points
1,228 views
0 votes
1 answer

What is the default priority of a thread in java?

By default, in Java, when a thread ...READ MORE

answered Nov 29, 2023 in Java by Zoya
455 views
+5 votes
4 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,450 points

edited Nov 7, 2018 by Omkar 81,393 views
0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20, 2019 in Java by Sirajul
• 59,230 points
2,358 views
0 votes
1 answer

difference between wait() and sleep() in java

We can find a big difference between ...READ MORE

answered Apr 26, 2018 in Java by developer_1
• 3,350 points
1,258 views
0 votes
2 answers

Does Java thread.sleep() puts swing ui to sleep?

You are correct about the code putting ...READ MORE

answered Oct 24, 2018 in Java by Sushmita
• 6,920 points
5,162 views
+1 vote
1 answer

Multithreading in Java with priorities

HI, @Juan, By default, a thread inherits the priority of its parent thread. ...READ MORE

answered Nov 6, 2020 in Java by Gitika
• 65,770 points
2,585 views
0 votes
1 answer

What is the difference between Runnable and extends Thread

Runnable is the preferred way to create ...READ MORE

answered May 1, 2018 in Java by sharth
• 3,370 points
1,190 views
0 votes
3 answers

Setting time zone of a java.util.Date

Using Java 8 Java 8 introduced a new Date-Time ...READ MORE

answered Dec 15, 2020 in Java by Gitika
• 65,770 points
56,916 views
0 votes
1 answer

How do you produce a double in Java

double num = 5; When you do this, ...READ MORE

answered Oct 4, 2018 in Java by anto.trigg4
• 3,440 points
886 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP