user3672051
user3672051

Reputation:

Executing one thread at a time sequentially

I have several threads being created in a for loop like this:

for (int i = 0; i<5; i++) {
   new Thread() {
       //do stuff
   }
}

but I need to make sure that these threads execute one after the other rather than all at the same time.

what is the best way to do this?

Upvotes: 1

Views: 1896

Answers (3)

uraimo
uraimo

Reputation: 19851

Use an ExecutorService with a pool size of 1 to execute your jobs sequentially (clean and simple solution).

If you need a quick example:

    Executor executor = Executors.newFixedThreadPool(1);
    for(int i=0;i<100;i++){
        final int idx=i;
        executor.execute(new Runnable(){
            public void run(){
               System.out.println("I'm thread #"+idx); 
            }
        });
    }

This will execute 100 Runnable sequentially, and each one will print its index.

See the official documentation for more details.

Upvotes: 9

Kumar Abhishek
Kumar Abhishek

Reputation: 192

Visit https://docs.oracle.com/javase/tutorial/essential/concurrency/join.html

I think thread join is what you want

Upvotes: 0

Ahmet Karakaya
Ahmet Karakaya

Reputation: 10147

for (int i = 0; i<5; i++) {
   Thread a = new Thread() {
       //do stuff
   };
a.start();
a.join();
}

Upvotes: 1

Related Questions