Thread confusion....
I having some conceptual problems with Threads. When starting an object that either extends Thread or implements Runnable, how should this be done? In my constructor, I do this: -
public SomeObject(){
this.myThread =new Thread(this);
this.myThread.start();
}
...which (by my reckoning) should kick off the thread and start the run() method where all my work is done.
If I want the threaded object to run indefinitely, should the run method have an infinite loop within it or does the run() method loop automatically?
Also, what is the purpose of the Thread. sleep() method? Do I need to use this somewhere within my run() method in order for the threaded object to devote time to other Threads? If so, how much time should I devote to the sleep()?
One last thing, since the Thread.stop() method has been deprecated, how you you cleanly stop a thread from executing? Perhaps have a public method that sets a boolean and then have a while loop within the run() method that only executes as long as this boolean is true?
Please do not point me at the Sun threads tutorial, if you'd be so kind. I've read it and also some other tuts on Threads, but I just need these questions answered. There is a lot to be said for talking to other programmers about this stuff rather than documentation. :) I know the tolerance here is low if the perception is that I am too dumb to read the tutorials, but I have....I am just having some problems with the finer points. Threads have been my all-time greatest problem with Java....all the way back to my uni days. I feel as though I have almost enough knowledge now to crack it, I just need a nudge in the right direction :)
If Jverd is reading this and firing up his flamethrower, have mercy. You are by far and away the most intimidating person I have ever encountered on any forums anywhere and although we've not had much occasion to annoy one another, I live in fear of your scorn. Sad but true. :)
Thanks for any infomation.....obviously, if you feel I'm being biblically thick, feel feel to link to the docs and just add a sarcastic footnote pointing out *why* I'm being dumb :)
I thank you. Its New Years Eve tomorrow, so I hope you all have a great time drinking or spending time with your partners or whatever. Personally, I'm going to a house party with friends where I intend to drink good English ale. I'm trying to convince everyone to go out for a thai green curry as well, but I think the drinking on couches is taking priority. :)
Amusing, if long and rambling post. ;)
> I having some conceptual problems with Threads. When
> starting an object that either extends Thread or
> implements Runnable, how should this be done? In my
> constructor, I do this: -
>
> > public SomeObject() {
>this.myThread = new Thread(this);
>this.myThread.start();
> }
>
Assuming the above "implements Runnable" and contains a run() method, it's "alright". If it extended thread, you obviously wouldn't instantiate a new thread within the constructor.
I say "alright" because it works, though I normally wouldn't start a thread within the constructor of a runnable, if only for the reason of keeping the code more general. If done this way, you have no way of creating the runnable object without starting a thread which runs it. For very simple cases, it's a shortcut I might take.
>
> ...which (by my reckoning) should kick off the thread
> and start the run() method where all my work is done.
>
>
> If I want the threaded object to run indefinitely,
> should the run method have an infinite loop within it
> or does the run() method loop automatically?
run() will be called once by the new thread. If you need it to repeat, you've got to explicitly provide a loop within this method.
> Also, what is the purpose of the Thread. sleep()
> method? Do I need to use this somewhere within my
> run() method in order for the threaded object to
> devote time to other Threads? If so, how much time
> should I devote to the sleep()?
sleep() allows you to tell the thread to pause for a finite period of time. It's not intended to give other threads a chance to progress -- the yield() method does that. In Java, the behavior of threads is loosely defined and different implementations have a lot of leeway in how thread scheduling happens. If the implementation does not do timeslicing and you have multiple threads running with the same priority, then it's possible for a long-running thread to monopolize the CPU, and other threads to starve. This is not an issue on Windows and Linux JREs... it might be an issue on small devices such as PDAs. The yield() method suggests to the scheduler to give other threads a chance to run.
> One last thing, since the Thread.stop() method has
> been deprecated, how you you cleanly stop a thread
> from executing? Perhaps have a public method that
> sets a boolean and then have a while loop within the
> run() method that only executes as long as this
> boolean is true?
Exactly. Remember to use proper thread safety techniques when accessing data which is (or potentially could be) read from and/or written to by multiple threads. This includes volatile and synchronized.
JN_a at 2007-7-8 1:53:01 >

Hmmm......on reflection....assuming that the run() method does not loop automatically, I guess the thread will terminate on its own as soon as the run() method finishes?
Sorry....I'm just thinking about it now. Amazing how posting a topic can focus the old brain. :)
Don't let that put you off replying....I'm fully aware that most of the programmers here are much better at this stuff than I am, so all input welcome.
> > public SomeObject() {
>this.myThread = new Thread(this);
>this.myThread.start();
> }
>
>
That looks valid, but I don't usually do it that way. I don't think it's too bad, but it seems cleaner to keep the thread and my object separate, and wait for an explicit start call, rather than starting on creation.
> ...which (by my reckoning) should kick off the thread
> and start the run() method where all my work is done.
Yep. Assuming that class implements Runnable (better) or extends Thread (not as good, OO-wise).
> If I want the threaded object to run indefinitely,
> should the run method have an infinite loop
Yep. Usually with something like if (isDone()) { break; } at the beginning so you can stop the thread if you want to. (You have to provide setDone/isDone, of course.)
> within it
> or does the run() method loop automatically?
Nope.
> Also, what is the purpose of the Thread. sleep()
> method?
To force a thread to stop for a fixed period of time. (Well, actually, it will stop for at least that long. It might be longer.)
> Do I need to use this somewhere within my
> run() method in order for the threaded object to
> devote time to other Threads?
Nope.
> One last thing, since the Thread.stop() method has
> been deprecated, how you you cleanly stop a thread
> from executing?
Have it check a flag (e.g. if (isDone()) ) each time through its loop.
> Perhaps have a public method that
> sets a boolean and then have a while loop within the
> run() method that only executes as long as this
> boolean is true?
Yep. Or if, as in my example, it's called "done," then only execute as long as it's false. :-)
> Please do not point me at the Sun threads tutorial,
> if you'd be so kind. I've read it and also some other
> tuts on Threads, but I just need these questions
> answered. There is a lot to be said for talking to
> other programmers about this stuff rather than
> documentation. :)
Agreed. And if you state that you've looked at certain resources and didn't find the answers there, you'll be more likely to either get the answers, or get pointed to the relevant parts of those resources that you may have missed or to other resources.
> I know the tolerance here is low if
> the perception is that I am too dumb to read the
> tutorials, but I have..
Nope. Not about being to dumb. It's just that if somebody asks a question that we think is answered elsewhere, we'd rather have you read that yourself than to regurgitate what somebody else already wrote. If, as you did, you've read it but either didn't find the answer to your question or didn't understand something, then that's fine. Just make that known here (as you did) so people don't send you back to read what was already not helpful to you.
(Though I'm surprised this wasn't covered in that tutorial.)
> If Jverd is reading this and firing up his
> flamethrower, have mercy. You are by far and away the
> most intimidating person I have ever encountered on
> any forums anywhere and although we've not had much
> occasion to annoy one another, I live in fear of your
> scorn. Sad but true. :)
LOL
I've got an undeservedly bad rep. I only rip new ones on people who are blatantly lazy or rude. There are plenty of other times when I'm blunt, but that's mainly in the interest of economy, rather than out of any desire to bash. I think those times combined with the cases that I'm truly an asshole have given people the wrong impression of me. It keeps the kids off my lawn though.
>sleep() allows you to tell the thread to pause for a finite period of time. It's not intended
>to give other threads a chance to progress -- the yield() method does that.
Excellent. So essentially....if I don't need the thread to pause for a finite amount of time, I don't especially need to worry about the sleep method? I was worried that I needed to utilize this in order for other threads to execute or something. :)
Indirectly, I think you might have answered another question I've been trying to find out about......in regards to the volatile keyword. If I read you correctly, it acts on member variables in the same manner that synchronized acts on methods.....to order the execution (or reading/writing to) of member variables which might be accessed by different threads possibly at the same time. I only ask, because I'm hoping to take my SCJP exam sometime in the next few months and the volatile keyword cropped up in one of the mocks I was looking at. Cheers. :) I had lots of trouble finding a definitive answer to what it actually does, but your post confirmed my hunch, at least.
I will of course refer you to that dreaded tutorial:
http://java.sun.com/docs/books/tutorial/essential/threads/lifecycle.html
All of the answers are on that page.
>which (by my reckoning) should kick off the thread and start the run() method
> where all my work is done.
Yes. That is right.
>If I want the threaded object to run indefinitely, should the run method have an
>infinite loop within it or does the run() method loop automatically?
You need to specify an infinite loop yourself ... one that exits gracefully.
>what is the purpose of the Thread. sleep() method? Do I need to use this
>somewhere within my run() method in order for the threaded object to devote
>time to other Threads? If so, how much time should I devote to the sleep()?
Yes. How long depends on what the thread is doing. How often should it be "running"? The clock example in the tutorial page sleeps for 1 second, and every second (or so) repaints itself.
>how you you cleanly stop a thread from executing? Perhaps have a public
>method that sets a boolean and then have a while loop within the run() method
>that only executes as long as this boolean is true?
That sounds fine to me.
The example uses the test of comparing the thread to the currently running thread. They seemed to indicate there was some reason for doing that, and I don't think it hurts to copy their example in this case.
Good luck,
evnafets
>That looks valid, but I don't usually do it that way. I don't think it's too bad, but it seems
>cleaner to keep the thread and my object separate, and wait for an explicit start call,
>rather than starting on creation.
Thanks Jverd for your kind reply :) Just to call you on the above......what is your reasoning for this? Surely you'd want to kick off the the thread on object creation if its a threaded object? I mean, thats its job (to run as a thread), so I was just wondering why you think its better to wait for an explicit call to start(). I'm not doubting you, I'm just enquiring. What sort of scenario would you envisage where you'd want to create the object yet not kick off the thread once the constructor has completed?
> >sleep() allows you to tell the thread to pause for a
> finite period of time. It's not intended
> >to give other threads a chance to progress -- the
> yield() method does that.
>
And in general, I'd advise against calling yield. It's better to let the scheduler figure out which threads should run when, as it has more complete information than you do.
I suppose if you have one thread that's doing a lot of CPU-intensive stuff, and you want to give an I/O thread that may have been blocking time to do its stuff (in case it unblocks in the middle of your long calcuations) then it might be useful. Otherwise I'd say avoid it.
> Excellent. So essentially....if I don't need the
> thread to pause for a finite amount of time, I don't
> especially need to worry about the sleep method?
Correct.
> Indirectly, I think you might have answered another
> question I've been trying to find out about......in
> regards to the volatile keyword. If I read you
> correctly, it acts on member variables in the same
> manner that synchronized acts on methods.....to order
> the execution (or reading/writing to) of member
> variables which might be accessed by different
> threads possibly at the same time.
I don't think I'd look at it quite that way. Volatile just means that whenever a the variable is read/written, it must be from/to main memory, not the thread's local copy. In theory, if it's not atomicity you're worried about, just making sure that threads see each others' writes, then declaring a variable volatile should be equivalent to synchronizing all access to that variable (since entering and leaving a sync block requires flushing from/to main mem). However, I've heard that volatile isn't always implemented right, and there seem to be a lot of misunderstandings about its use, so just syncing all access to the variables in question might be a safer way to go. At least until you've had a chance to understand the subtleties better.
> >what is the purpose of the Thread. sleep() method?
> Do I need to use this
> >somewhere within my run() method in order for the
> threaded object to devote
> >time to other Threads? If so, how much time should I
> devote to the sleep()?
> Yes.
Er, no.
> Thanks Jverd for your kind reply :)
You're welcome. Kind replies from me aren't as rare as you might think though.
> Just to call you
> on the above......what is your reasoning for this?
Because I said so and anybody who disagrees with me is a racist. ;-)
> Surely you'd want to kick off the the thread on
> object creation if its a threaded object?
Nope. Not even sure what you mean by "threaded object." (Picturing nuts & bolts in my pathetically literal mind.)
> I mean,
> thats its job (to run as a thread),
The Runnable's job is to be able to run in a separate thread when the thread is started. But it's job is not to start that thread, IMHO. Just a division of responsibility thing.
Sometimes there might be configuration involved before starting, or I may want the controlling program to do stuff with the runnables--store them in a list, wait for some external stimulus to start them, etc.--before starting.
Also, the purpose of a constructor is to initialize the state of the object. You shouldn't usually have a lot of business action happening in the constructor.
I don't think it's that big a deal. I just try to keep the lines of responsibility clear.
>Amusing, if long and rambling post. ;)
Yes, its a bad habit I have. I hate terse posts. Next time, feel free to pick out the relevent parts and ignore the rest :)
If its any help, I've actually knocked it on the head for the day, so I've had a beer or two now. Pity the nerd who still thinks about threads whilst drinking. Actually, I'm not sure if thats funny or tragic. :)
>The Runnable's job is to be able to run in a separate thread when the thread is started.>But it's job is not to start that thread, IMHO. Just a division of responsibility thing.Aha. Gotcha. :) I see where you're coming from now.
> >The Runnable's job is to be able to run in a
> separate thread when the thread is started.
> >But it's job is not to start that thread, IMHO. Just
> a division of responsibility thing.
>
> Aha. Gotcha. :) I see where you're coming from now.
Good.
Now get off my lawn, ya punk.
> Pity the> nerd who still thinks about threads whilst drinking.What's wrong with that?> Actually, I'm not sure if thats funny or tragic. :)It's a sign of being cool, suave, and studly.
>Now get off my lawn, ya punk.Tsch. I could have been trying to sell ya cookies, you know.
>What's wrong with that?Ahh....the relief is almost palpable!
Thanks for all the replies everyone. Thats cleared up pretty much all the uncertainties I've been having on threads, so thanks for that. Now I can drink my beer knowing exactly what refactoring I need to do to my code in the morning. Hope you all have a stellar New Years tomorrow night.