Streams; Creating a separate thread for periodic execution of something

As a complement to my current application, I need to create a separate thread that will periodically perform some processing

I am creating a new class to do all this, and this class will be loaded when my application starts.

This is what I have so far:

public class PeriodicChecker extends Thread
{
    static
    {
        Thread t = new Thread(new PeriodicChecker());
        while(true)
        {
            t.run();
            try
            {
                Thread.sleep(5000l);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * Private constructor to prevent instantiation
     */
    private PeriodicChecker()
    {

    }

    @Override
    public void run()
    {
        System.out.println("Thread is doing something");
        // Actual business logic here, that is repeated
    }

}

I want to make the constructor private so that other people do not try to instantiate this class. How can I achieve this?

Also, is there anything bad about my implementation of such requirements? I create only one thread that will run, and then sleep, did I miss something obvious? I did not work with threads until

+5
5

... :

  • start() (), , .
  • start() , . TERMINATED, , .
  • , , , , Thread , .

, , .

, - , :

public class PeriodicChecker extends Thread
{
    @Override
    public void run()
    {
        while(true) {
           System.out.println("Thread is doing something");
           Thread.sleep(5000);
        }
    }

}

public OtherClass {
   public static void main(String args[]) {
      Thread t = new PeriodicChecker();
      t.start();
   }
}

, , , , .

+9

Java ScheduledExecutorService . . Timer - , , ScheduledExecutorService over Timer .

+12
+4

, , . , , new PeriodicChecker().

, , :

-, . , , , . , .

-, , , , , , :). , start() . run(), , , run() .

, , -, - Thread, Runnable. , .

, , , :

public class Main {

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    System.out.println("Thread is doing something");
                    Thread.sleep(5000);
                }
            }
        }).start();
    }

}
+3

, Thread . - , , , Thread.

, extends Thread, Runnable - Timer.

+2

All Articles