简体   繁体   中英

Java Thread Executor Submit Main Class

I have an application with a main class that sets up a thread executor for a few other runnable classes however I want an update method in the main class to be called regularly also so is it best to create a thread like in the example below OR submit the class to the thread executor declared inside it (something like in the example below the example)?

Feels wrong using a mixture of thread executors and starting standard threads.

Use standard thread call for main classes updates?

public class Test {

private ScheduledExecutorService scheduledThreadPool; //used for creating other threads
private Thread t;

public Test() {
    t = new Thread() {
        @Override
        public void run() {
            try {
                while (true) {
                    processUpdates();
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                logger.error(e);
            }
        }
    };
}

private void processUpdates() {
    //do some stuff
}

}

OR use thread executor for not just the other runnable classes but the main class itself?

public class Test implements runnable {

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);

public Test() {
    scheduledThreadPool.scheduleWithFixedDelay(this, 0, 10, TimeUnit.MILLISECONDS);
}

@ Override
public void run() {
    processUpdates();
}

private void processUpdates() {
    //do some stuff
}

}

Thanks!

Always use thread pools over plain old threads : it gives you much more control over the execution of your threads.

If you want all your threads to run in parallel, you can always use an unlimited thread pool, which is discouraged because Thread is costly in memory.

In your case, the use of a ScheduledExecutorService is even more recommended since it avoids the sleep instruction in your thread implementation. It gives better performance and a much better readability.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM