Managing Threads

Hullo.

I've been fiddling around with multi-threading but it's still very new to me. For the code below, please just assume the existence of classes LinkedCollection (which implements java.util.Collection) and Berk (which implements java.lang.Runnable), as they aren't a part of my question.

LinkedCollection<Thread> threads =new LinkedCollection<Thread>(false);

for (int i = 0; i < 10; i++)

threads.add(new Thread(new Berk(),"Thread " + i));

for (Thread t : threads)

t.start();

boolean running;

do{

running =false;

for (Thread t : threads)

if (t.isAlive()){

running =true;

break;

}

}while (running);

The first for loop creates and adds to a collection ten Threads that each perform Berk. The second for loop starts each thread in turn. The while loop iterates until it finds that none of the threads in the collection are still alive.

Is there a more concise way to do this sort of management? [I don't mean by somehow rearranging what I've just done, but rather --> ] Does Java provide some structure or pattern to monitor and manage threads with? I was looking at ThreadGroup but it doesn't seem to provide the answer...

Thanks for info and help.

Grape

[1931 byte] By [ProGrapea] at [2007-11-27 5:51:21]
# 1
Firstly, your third loop is going to sit spinning and consuming a lot of CPU time whilst it waits.Secondly, checkout the Thread.join() method.
dannyyatesa at 2007-7-12 15:40:24 > top of Java-index,Core,Core APIs...
# 2
It seems to me that Thread.join only lets me wait for one thread at a time (as I understand it so far), whereas what I want to do is to wait for a handfull of them.
ProGrapea at 2007-7-12 15:40:24 > top of Java-index,Core,Core APIs...
# 3
Take a look at java.util.concurrent.ExecutorService.invokeAll(Collection<Callable><T>>, long, TimeUnit).Here you can wait for a number of threads to finish their work
anand_nalyaa at 2007-7-12 15:40:24 > top of Java-index,Core,Core APIs...
# 4

> It seems to me that Thread.join only lets me wait for

> one thread at a time (as I understand it so far),

> whereas what I want to do is to wait for a handfull

> of them.

And how is that different from your current solution which checks the threads one at a time in a loop?

Really, if you can't figure out something this simple given the extremely large pointer I gave you, you shouldn't be dabbling with thread programming - it will just end up with tears.

for (Thread t: threads) {

t.join();

}

// all threads are now finished

(There's some exception handling you'll need to add here...)

dannyyatesa at 2007-7-12 15:40:24 > top of Java-index,Core,Core APIs...