| Author |
Starting new threads
|
Radha Lakshmi
Greenhorn
Joined: Apr 20, 2009
Posts: 1
|
|
Hi,
I am new to java concurant programming and trying out with few examples.I wanted to start 5 threads and stop them by printing (System.out.println) Thread1 started,Thread2Started,Thread3Started etccc then Thread1stopped,Thread1stopped etccc..
I have writen the below program.Please help tp change it to produce all started messages once then stopped messages.
public class SimpleThread {
public static void main (String[] args) {
for(int i=0;i<5;i++)
new RunnableTask(i).start();
}
}
class RunnableTask extends Thread
{
RunnableTask(int i)
{
super(String.valueOf(i));
}
public void run()
{
System.out.println("Thread "+this.getName()+"Started");
System.out.println("Thread "+this.getName()+"Stopped");
}
}
Regards
Radha
|
 |
Steve Luke
Bartender
Joined: Jan 28, 2003
Posts: 3087
|
|
Well, this might not be as simple as you had hoped. Threads tend to execute in their own order unless you force order upon them using various synchronization tools. To get an idea of how synchronization tools work, I suggest reading the Java Concurrency Tutorial.
For your application, this task becomes relatively simple using one of the new(ish) locking mechanisms from the java.util.concurrent package. Basically, you have 5 tasks, and want to make sure they all reach a certain point (after the 'started' message) before they can continue. This is the perfect use for the CountDownLatch. An example:
Just as an FYI, it is normally frowned upon to extend Thread, unless you absolutely need to. Instead, implement the Runnable interface and pass it to a new thread:
|
Steve
|
 |
 |
|
|
subject: Starting new threads
|
|
|