views:

180

answers:

6

Greetings,

I'm trying to solve the following task: Given N threads, make them run consecutively. For example each of them should output it's number in the following order:

Thread 1 Thread 2 ... Thread N

How do I do this, using only wait/notify and synchronized methods (without flags, etc)?

P.S. Sorry for my poor english :)

+3  A: 

How about:

thread1.run();
thread2.run();
thread3.run();

New threads are unnecessary unless concurrent execution is needed. A single thread can execute the Threads' bodies consecutively.

If this straightforward approach doesn't work (that is, satisfy a teacher's expectations for a contrived homework exercise), please clarify the problem in your question.

erickson
Doing just that, it's not guaranteed that it will print "Thread 1, Thread 2, Thread 3"
Alexander Pogrebnyak
@(Alexander Pogrebnyak) Yes it will.
NawaMan
Alexander, he's calling .run(), not .start() :)
Grandpa
A: 

In pseudo-code, it would look like this :

synchronized (var) 
{
  var.wait();
  print(var);
  var.notifyAll();
}
svlada
A: 

I assume you can't edit each thread code. So here is is

...
final Thread[] Threads = ...;
Thread aSuperThread = new Thread() {
    public void run() {
        for(Threads T : Threads)
            T.run();
    }
};
aSuperThread.start();
...
NawaMan
A: 

Have you tried joining the threads?

I will not providing more clues, as it is a homework.

Alexander Pogrebnyak
+7  A: 
thread1.start();
thread1.join();

thread2.start();
thread2.join();

...

The call to .join() will wait for the thread to complete before continuing.

highlycaffeinated
+1, but you probably want a loop rather than thread1/thread2 etc. :-)
Brian Agnew
A: 

Have you heard about Executors?

// create ExecutorService to manage threads                        
ExecutorService threadExecutor = Executors.newFixedThreadPool( 3 );
threadExecutor.execute( task1 ); // start task1
threadExecutor.execute( task2 ); // start task2
threadExecutor.execute( task3 ); // start task3

Where task1, task2 and task3 are objects that implement the runnable interface. Executors are available since Java 5 More info: http://www.deitel.com/articles/java%5Ftutorials/20051126/JavaMultithreading%5FTutorial%5FPart4.html

Mogox