wood burning stoves
The moose likes Threads and Synchronization and the fly likes Starting new threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Starting new threads" Watch "Starting new threads" New topic

Starting new threads

Radha Lakshmi

Joined: Apr 20, 2009
Posts: 1

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)
public void run()
System.out.println("Thread "+this.getName()+"Started");
System.out.println("Thread "+this.getName()+"Stopped");

Steve Luke

Joined: Jan 28, 2003
Posts: 4181

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:

I agree. Here's the link: http://aspose.com/file-tools
subject: Starting new threads
It's not a secret anymore!