Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to stop a Thread?

I'm trying to implement a separate Thread in my project. Every hour a scheduler starts a thread to get files from a server and store them in my database.

My code works as it should. Since the scheduler starts a new Thread every hour, I don't know if I need to stop the Thread manually or not?

 try {
        Runnable task = new MyClass();
        Thread thread = new Thread(task);
        thread.start();

 } catch (Exception ex) {
        System.err.println("Exception-Thread: " + ex.getMessage());
 }

My Class (runnable)

  public class MyClass implements Runnable {
        @Override
        public void run() {

            try {
                //Do stuff...
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
like image 219
Mihawk Avatar asked May 30 '26 21:05

Mihawk


2 Answers

If you do not have a permanent loop or something similar inside the Runnable, then no you don't need to.

like image 129
Murat Karagöz Avatar answered Jun 02 '26 11:06

Murat Karagöz


As long as the thread has not chance of doing infinite loop Such as using while loop. Thread will stop once all the tasks in Runnable are done.

like image 45
alikhtag Avatar answered Jun 02 '26 10:06

alikhtag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!