Sequential streams in Java

Greetings,

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

Topic 1 Topic 2 ... Topic N

How can I do this using only waits / notifications and synchronized methods (no flags, etc.)?

PS Sorry for my poor english :)

+2


source to share


6 answers


thread1.start();
thread1.join();

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

...

      



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

+7


source


What about:

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

      



New threads are not needed unless parallel execution is required. A single thread can execute Threads bodies sequentially.

If this simple approach does not work (i.e. meets teachers' expectations for contrived homework), please clarify the problem in your question.

+3


source


Have you tried to join ing to those?

I won't give more hints as this is homework.

+1


source


In pseudocode, it looks like this:

synchronized (var) 
{
  var.wait();
  print(var);
  var.notifyAll();
}

      

0


source


I am guessing that you cannot edit every code in the stream. So here

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

      

0


source


Have you heard about performers?

// 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

      

In cases where task1, task2, and task3 are objects that implement the runnable interface. Executors are available since Java 5 More information: http://www.deitel.com/articles/java_tutorials/20051126/JavaMultithreading_Tutorial_Part4.html

0


source







All Articles