Answer the question
In order to leave comments, you need to log in
Should I use a separate thread for each task in Java?
There is a program that must periodically perform certain actions (check the database for new records, check for files, etc.).
The question is, is it worth creating a separate thread to perform each of the tasks, given that most of the time these threads will sleep, or just get by with a regular timer?
Answer the question
In order to leave comments, you need to log in
If there are any events to which the application must immediately respond, then of course the flows. If the main task of the application is these checks, then the timer is enough.
I would do something like this if you need to check once every N time.
public class Main {
private static int period = 60; //Default period
private static final TimeUnit PERIOD_TIME_UNIT = TimeUnit.MINUTES;
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
System.out.println(String.format("Worker work period %d %s", period, PERIOD_TIME_UNIT));
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
//код который должен запускатся по таймеру
}
}, 0, period, TimeUnit.MINUTES);
}
}
ThreadPoolExecutor
one. For this, I have a class with callbacks written like the Android AsyncTaskonPostExecute
onPreExecute
doInBackground
, to which you give Runnable
it to execute them.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question