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 20, 2018 in Java by 93.lynn
• 1,590 points
47 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 20, 2018 by anto.trigg4
• 3,420 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,150 points
98 views
+5 votes
3 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,380 points

edited Nov 6, 2018 by Omkar 11,447 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 in Java by Sirajul
• 41,000 points
219 views
0 votes
2 answers

How to create a 2-D array in java?

int[][] multi = new int[5][]; multi[0] = new ...READ MORE

answered Jul 16, 2018 in Java by Daisy
• 8,050 points
63 views
0 votes
1 answer

difference between wait() and sleep() in java

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

answered Apr 25, 2018 in Java by developer_1
• 3,300 points
83 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,880 points
734 views
0 votes
1 answer

What is the difference between Runnable and extends Thread

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

answered Apr 30, 2018 in Java by sharth
• 3,350 points
139 views
0 votes
2 answers
0 votes
1 answer

Setting time zone of a java.util.Date

You can make use of the following ...READ MORE

answered Aug 14, 2018 in Java by anto.trigg4
• 3,420 points
5,257 views
0 votes
1 answer

How do you produce a double in Java

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

answered Oct 3, 2018 in Java by anto.trigg4
• 3,420 points
34 views