There is one interesting question many people have got during their interviews -
How will you execute the threads in a particular order like - T4 will execute after T3, T3 will execute after T2 & T2 will execute after T1
Well here I am putting my thoughts only, & if you dont agree & have reasons for that please let me know.
I feel there can be various ways to execute the threads in particular order, but again I would like to know about the various scenarios in which such code will be executed.
Like -
1) Can we make any changes in the code of those Thread classes.
2) Where we want to decide that order?
3) Which point will be controlling this order or where you are executing these threads in that order.
4) Do we know the order of each thread during the start or that order will be decided during the runtime.
So depending on the answers of the above, I think we can use join() or wait/notify or see in countdownlatch or cyclicbarrier APIs.
But I was thinking about one more way, if we are creating such Thread classes which need to be executed in that order.
Here, I think, after tweaking the same way, one can decide on the order of the threads at the runtime by providing the order & next values at the runtime -
How will you execute the threads in a particular order like - T4 will execute after T3, T3 will execute after T2 & T2 will execute after T1
Well here I am putting my thoughts only, & if you dont agree & have reasons for that please let me know.
I feel there can be various ways to execute the threads in particular order, but again I would like to know about the various scenarios in which such code will be executed.
Like -
1) Can we make any changes in the code of those Thread classes.
2) Where we want to decide that order?
3) Which point will be controlling this order or where you are executing these threads in that order.
4) Do we know the order of each thread during the start or that order will be decided during the runtime.
So depending on the answers of the above, I think we can use join() or wait/notify or see in countdownlatch or cyclicbarrier APIs.
But I was thinking about one more way, if we are creating such Thread classes which need to be executed in that order.
Here, I think, after tweaking the same way, one can decide on the order of the threads at the runtime by providing the order & next values at the runtime -
Note :- Above I have used sleep(), as I am not using lock concept here. If you have certain resource being shared among these threads & requires lock then use wait() instead. Here I am providing the value of next or we know which thread will be next to execute. So I am setting the state in predefined order. But suppose your requirement is to decide this state at runtime then you can add that logic instead, to have interesting implementation of 'State' pattern.