Worker Thread in Java

后端 未结 4 2164
天命终不由人
天命终不由人 2021-02-08 07:13

I need to read the data from a table every minute through thread & then perform certain action.

Should I just start a thread & put it in sleep mode for 1 minute

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-08 07:39

    As so often, the Java 5 extensions from the java.util.concurrent package are a huge help here.

    You should use the ScheduledThreadPoolExecutor. Here is a small (untestet) example:

    class ToSomethingRunnable implements Runnable {
        void run() {
            // Add your customized code here to update the contents in the database.
        }
    }
    
    ScheduledThreadPoolExecutor executor = Executors.newScheduledThreadPool(1);
    ScheduledFuture future = executor.scheduleAtFixedRate(new ToSomethingRunnable(), 
         0, 1, TimeUnit.MINUTES); 
    
    // at some point at the end
    future.cancel();
    executor.shutdown();
    

    Update:

    A benefit of using an Executor is you can add many repeating tasks of various intervals all sharing the same threadpool an the simple, but controlled shutdown.

提交回复
热议问题