Run Java Threads sequentially

Use ExecutorService in java.util.concurrent package. More precisely use Executors.newSingleThreadExecutor();


You could use Executors.newSingleThreadExecutor(), but strictly speaking this launches only one Thread, so may not be expected solution.

The simpliest solution using just Thread class:

Thread1.start();
Thread1.join();
Thread2.start();
Thread2.join();
Thread3.start();
Thread3.join();

(I omitted exception handling for clarity, Thread.join() can throw InterruptedException)


The simplest answer is

Thread1.run();
Thread2.run();
Thread3.run();

The problem with unrealistic questions is they often have an uninformative answer. ;)

The whole point of having threads is to run them concurrently. If you are not doing that at all, don't use threads.

You might say that; you cannot call the run() method, in which case you cannot use ThreadPoolExecutor because it calls the run() method for you. i.e. thats what submit() eventually does.

EDIT: The results are completely deterministic, becaus ethe fact that there is a Thread involved is irrelivent.

static class PrintThread extends Thread {
    public PrintThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++)
            System.out.println(getName() + ": " + i);
    }
}

public static void main(String args[]) {
    Thread thread1 = new PrintThread("A");
    Thread thread2 = new PrintThread("B");
    Thread thread3 = new PrintThread("C");

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

Prints

A: 0
A: 1
.. deleted ..
C: 98
C: 99

as expected.