Java中的Executor和Daemon [英] Executor and Daemon in Java
问题描述
我有一个MyThread对象,当我的应用程序通过服务器加载时,我将其实例化,我将其标记为守护程序线程,然后在其上调用 start()
。只要应用程序处于活动状态,该线程就会等待队列中的信息。
我的问题/问题是:目前MyThread正在扩展Thread,因为我将它标记为守护进程,并且我读到了如何实现Runnable以及使用Executor更令人满意。所以我想问的是,如果MyThread将实现Runnable而不是扩展Thread(当然会被重命名)并且我将使用 newSingleThreadScheduledExecutor()
如何,什么或者可能在哪里,我将标记为守护进程。
我希望我没有弄乱一些条款,请原谅我,因为多线程环境的某些部分对我来说是非常新的。
I have a MyThread object which I instantiate when my app is loaded through the server, I mark it as a Daemon thread and then call start()
on it. The thread is meant to sit and wait for information from a queue as long as the application is active.
My problem/question is this: Currently MyThread is extending Thread because I mark it as Daemon and I read about how it's more prefferable to implement Runnable and to use Executors. So what I wanted to ask is if MyThread will implement Runnable instead of extending Thread (and of course will be renamed) and I'll use newSingleThreadScheduledExecutor()
how, what or maybe where, do I mark something as Daemon.
I hope I haven't made a mess of terms, please excuse me if I have as some parts of the multithreading environment are very new to me.
谢谢
Ittai
Thanks Ittai
更新:
我在我的应用程序中提到的模块是一个web-app,实际上有一些这样的线程排序和它们共同的作用是它们都是 ServletContext
作为成员出于各种原因。目前我将 Thread
扩展为 WebThread
,其中 ServletContext
为memebr和所有子类都可以利用它。如果我使用Executor和ThreadFactory切换到Runnable范例,基本上我需要有一个丑陋的 WebRunnable
混合实现 Runnable
并将 ServletContext
作为公共成员并让我的 ThreadFactory
实现 newThread(除了
。 newThread(Runnable arg0)
之外,WebRunnable arg0)
我不确定什么是最好的。
谢谢
Update:
The module I'm referring to in my app is a web-app which has a few threads actually of this sort and what they do have in common is that they all in the ServletContext
as a member for various reasons. Currently I extend Thread
to WebThread
which has the ServletContext
as a memebr and all subclasses can utilize this. If I switch over to the Runnable paradigm with the Executor and ThreadFactory than basically I need to have an ugly hybrid of WebRunnable
which implements Runnable
and has the ServletContext
as a public member and have my ThreadFactory
implement newThread(WebRunnable arg0)
in addition to newThread(Runnable arg0)
.
I'm not sure what's best.
Thanks
推荐答案
如果你正在使用预定的执行者,你可以提供 ThreadFactory 。这用于创建新线程,您可以根据需要修改这些线程(例如,使它们成为守护进程)。
If you're using a scheduled executor, you can provide a ThreadFactory. This is used to create new Threads, and you can modify these (e.g. make them daemon) as you require.
编辑:要回答您的更新,您的 ThreadFactory
只需要实现 newThread(Runnable r)
,因为你的 WebRunnable
是 Runnable
。所以没有真正的额外工作。
To answer your update, your ThreadFactory
just needs to implement newThread(Runnable r)
since your WebRunnable
is a Runnable
. So no real extra work.
这篇关于Java中的Executor和Daemon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!