[英]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. 如果希望所有线程并行运行,则始终可以使用无限线程池,因此不建议使用此线程池,因为Thread
在内存中的开销很大。
In your case, the use of a ScheduledExecutorService
is even more recommended since it avoids the sleep
instruction in your thread implementation. 在您的情况下,甚至建议使用ScheduledExecutorService
因为它避免了线程实现中的sleep
指令。 It gives better performance and a much better readability. 它具有更好的性能和更好的可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.