The last question (when I was there last) in the top url is what the effect of creating two 'Threads' with one 'Runnable' would be. Seems to work fine. (with the code commented out as mentioned in next posts) Why should you need two objects from 'Runnable' classes to create two 'Threads'? The thread objects created are new seperate objects anyway. Its not as if they contend for the one 'Runnable' object instance that was created, if I understand it correctly. If that's true the 'Runnable' object is actually useless except for the creation of the 'Thread' objects.
public Thread(Runnable target) Allocates a new Thread object. This constructor has the same effect as Thread(null, target, gname), where gname is a newly generated name. Automatically generated names are of the form "Thread-"+n, where n is an integer. Parameters: target - the object whose run method is called. See Also: Thread(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String)
[ September 19, 2002: Message edited by: Jim Crawford ]
Seems like the next thread is created on the next 'while' cycle in 'run()', if there is any. This behaviour doesn't make sense. Maybe because its not used correctly, but I thought it was worth exploring. So the one 'Runnable' object seems to be shared somehow... just can't think how yet.
I may be off the mark here, but I think the sort of thing you are playing with is like what happens with servlets. You have many threads traversing one servlet instance and that's why you should not try to store session state in a servlet's instance variables. Could be Something Completely Different of course... Over. -Barry
Originally posted by Jim Crawford: Why should you need two objects from 'Runnable' classes to create two 'Threads'? The thread objects created are new seperate objects anyway. Its not as if they contend for the one 'Runnable' object instance that was created, if I understand it correctly.
Actually in your original code, you passed the same Runnable object into your two Threads
in which case the Threads will "contend" on the common Runnable object. Here's a sample code:
Each Strider object is running on its own, well, thread, while two Threads are accessing the single Runner object in a multi-threaded manner.
Joined: Mar 22, 2002
If you created multiple Runnable objects and passed different instances to each Thread constructor, then each Thread will "have" its own exclusive Runnable object.
This code behaves like the first one.
Joined: Sep 08, 2002
Thanks! (wish I had more time to study... back at work today)