Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

multithreading - Executor and Daemon in Java

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.

Thanks Ittai

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check out the JavaDoc for newSingleThreadScheduledExecutor(ThreadFactory threadFactory)

It would be implemented something like this:

public class MyClass { 
    private DaemonThreadFactory dtf = new DaemonThreadFactory();
    private ScheduledExecutorService executor = 
                                 Executors.newSingleThreadScheduledExecutor(dtf);
    // ....class stuff.....
    // ....Instance the runnable.....
    // ....submit() to executor....
}

class DaemonThreadFactory implements ThreadFactory {
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r);
        thread.setDaemon(true);
        return thread;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...