Re: concurrency, threads and objects
Chris Uppal wrote:
Tom Forsmo wrote:
Creating only one object and creating a number of threads for that
objects run method, also seems wrong, for two reasons. 1) the object
could then not have any state unless it was to be shared and [...]
That is correct, but it may be the semantics that you want -- if several
threads have to share data for instance. (It's not the typical case, though.)
I didn't quite think of it like that...
[...] 2) when
reading the name of the thread all threads are named the same.
The name comes from the instance of Thread, and can be set independently of the
Runnable object that each thread executes.
I tried this but it did not work properly. What I did was this:
thr = new Thread[opt.getThreads()];
for(int i=0; i<opt.getThreads(); i++) {
thr[i] = new Thread(this);
thr[i].setName("thread num: " + i);
thr[i].start();
}
But I found out, just now, that if I use setName() inside run(), then it
works ok, why is that? the object is created outside run so changing its
state there should be ok, unless the object is reinitialised when run()
starts to execute.
Creating a number of objects with a thread for each is sort of like
creating many separate programs/processes, it seems like waste of
objects to start with. Why create as many objects as you would create
threads?
I don't know Posix threads, but I assume there is some way that you can ask the
system about a thread once created (is it still running, what groups does it
belong to, and so on). So there is a /something/ there that you can talk
about. In Java a "something" is always represented by an object, so in Java
there is an object (instance of Thread) which stands for each thread.
As an example, a thread couldn't have a name unless there was an object to hold
the name.
Sorry, what I meant was my defined objects, not the Thread objects. E.g.
I can define an class ClassA which implements Runnable. If I use 100
threads, I would create 100 ClassA objects, which means I would have 100
ClassA objects and 100 Thread objects.
thr = new Thread[opt.getThreads()];
for(int i=0; i<opt.getThreads(); i++) {
Runnable r = new ClassA();
thr[i] = new Thread(r);
thr[i].start();
}
Of course the Thread object is here composed of the ClassA object, so it
would be the same as if you extended a Thread class, but that is my
point. It seems like a waste of resources to have those 100 ClassA
objects lying around for no reason. A thread safe program requires
re-entrancy, which it in this example solves, not by having a re-entrant
object, but rather by just creating completely new objects avoiding the
entire issue... Sort of like starting 100 separate programs/processes.
This is where my perception clashes with java threads.
tom