Re: concurrency, threads and objects
A. Bolmarcich wrote:
Be careful to invoke getName() on the same object on which setName()
was invoked. Within run() you likely want to use an expression like
Thread.currentThread().getName()
that seemed to work, but I don't understand quite why.
Instead of posting partial code, please post a small complete program that
demonstrates the problem that others can compile and run.
(Please don't post comments in a thread where they don't belong, it
makes it difficult to understand what message and part of it you are
commenting.)
I was posting only the relevant parts of the code, all the other code
has nothing to do with the problem.
Not in the example code that posted. It had a loop whose body contained
thr[i] = new Thread(this);
That would create 100 Thread objects. The statement
thr[i].start();
later in the loop would invoke the run() method of the (single) object
referred by the keyword "this" 100 times.
Yes, but it starts the 100 threads (i.e. the thread objects), which all
executes within the same object, namely this.
In any case, it was the wrong code, it was supposed to be
thr = new Thread[opt.getThreads()];
for(int i=0; i<opt.getThreads(); i++) {
System.out.println("Starting Thread " + i);
thr[i] = new Worker();
thr[i].start();
}
this creates 100 worker objects and 100 threads objects
tom