I know this is strange, but i have a simple syntax question. Right now I'm working with a thread in the following format. The use of "setDaemon" in the run function does not work, as you apparently must set Daemon before you start the thread.

new Thread()
        {
            @Override
            public void run()
            {
                setDaemon(true); // This is what is causing the error. 
                while(true)
                {
                    //Update loop stuff
                }
            }
        }.start();

Is it possible to do something like what is below, where i move the set daemon near the "start()". However to do this will try to start void.

new Thread()
        {
            @Override
            public void run()
            {
                while(true)
                {
                    //Update loop stuff
                }
            }
        }.setDaemon(true).start();

So how would I do something so that I can setDaemon(true), and also start the thread, while maintaing this kind of formatting.

I'm sorry if this is a duplicate thread, but i've been unable to find anything talking about what I want to do.

Recommended Answers

All 5 Replies

When you do new Thread() {...}.start(); , you are creating an unnamed class and using it right where you declare it. I understand you are asking how to call setDaemon using this syntax, but I'm not sure it's possible. So my question is, why can't you create a named class for your thread instead? If you do that, then it won't be a problem to create the thread object, call setDaemon on it and then call start. ??

Yes, as Kramerd suggested, you'll need to create the Thread object, setDaemon(), and then start it.

The setDaemon() method is a void return, so you cannot chain it as you tried above. If setDaemon() returned a reference to itself then chaining would be possible.

All this makes sense, but does anyone have a solution?

I would try to keep this as an un named class for organization, and so that it shares the private variables of this class.

You don't have to name the class, just the reference you're creating.

Thread t = new Thread()
        {
            @Override
            public void run()
            {
                while(true)
                {
                    //Update loop stuff
                }
            }
        };
t.setDaemon(true);
t.start();

Awesome - that worked perfectly. I could have sworn I tried this, but I probably forgot to remove the .start() at the end.

Thanks again for your help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.