Ayusman Ayusman - 6 months ago 8
Java Question

is it possible to define execution order for a set of threads in java

My understanding is that threads in theory are executed in parallel. JVM decides; when a resource is available which thread to pick from the waiting thread queue (based on some algorithm).

Hence we can not provide/enforce a sequence of execution for threads.

Say my java application has 3 threads, t1, t2 and t3.

For some specific reason; I want the threads to execute in this order:
t3 then t1 and then t2.

Is it possible to do this? Does java provided any way of doing this?

Answer

Use an Executor:

executor.execute(runnable1);
wait();
executor.execute(runnable2);
wait();
executor.execute(runnable3);
wait();

And of course, each Runnable has to end with a notify() statement.

Comments