1

In my Java main method, need to spawn a single thread for a task. The thread does the task and sleeps for 30secs. repeatedly.

In my case, using Java executor framework threadpool may be an overhead. Hence thinking of spawning a single thread. Any comments?

kakoli
  • 423
  • 4
  • 8
  • 18

3 Answers3

2

You can use ScheduledExecutorService introduced in Java 5, which suits your purpose and uses ThreadPool as well.

public static void main(String[] args) {
    ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
    ex.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + ":" + Calendar.getInstance().getTime());
        }
    }, 0, 30, TimeUnit.SECONDS);

}

Output:

pool-1-thread-1:Fri Aug 22 09:56:50 IST 2014
pool-1-thread-1:Fri Aug 22 09:57:20 IST 2014
pool-1-thread-1:Fri Aug 22 09:57:50 IST 2014
pool-1-thread-1:Fri Aug 22 09:58:20 IST 2014

Also, ScheduledExecutorService is preferred over Timer [StackOverFlow Discussion On Timer Vs ScheduledExecutorService].

Community
  • 1
  • 1
Abhishek
  • 422
  • 4
  • 13
0

If you want to perform some task every 30 seconds, then Timer is best option I think. Timer will use a single thread to execute the task and you can schedule the task periodically.

Timer timer = new Timer();
timer.schedule(task, 30 * 1000);

I hope this would help you.

Loganathan Mohanraj
  • 1,736
  • 1
  • 13
  • 22
  • 2
    Like @Thilo mentioned, you'd be better off with a TheadPoolExecutorService; it's basically a new, generalized version of Timer that's Runnable-friendly. – David Ehrmann Aug 22 '14 at 04:24
0

The ScheduledExecutorService can create a single-threaded executor that can schedule commands to run after a given delay, or to execute periodically,which should work for you and the overhead is tiny.

 ScheduledExecutorService executor= Executors.newSingleThreadScheduledExecutor;

 //do your work evry 30 seconds,and you could define the delayed time to start
 executor.scheduleAtFixedRate(new CustomeTask(), YOUR_DELAY_TIME, 30, TimeUnit.SECONDS);

private static class CustomeTaskimplements Runnable {
    @Override
    public void run() {
       //Do any work you want
    }
}

If you do not want to use the Executors. You may do something like Thread.sleep(30000); in the while(true) loop in your method of Run() to achieve that.

JaskeyLam
  • 15,405
  • 21
  • 114
  • 149