Did you say that you know multi threading?
I also say the same.
So you know doing multithreading is not a joke & its tricky to do synchronization among
threads.
To test such knowledge, interviewer can ask -
Print Odd & Even numbers via different threads.
Here the problem seems quite easy and we can quickly decide that we will just create 2
separate threads to print Odd and Even numbers but the challenge comes when we need to
orchestrate this printing, synchronize the excecution of 2 threads.
For this we can have multiple ways but below I am giving 2 such ways & rest you can add in the comments sections.
Way 1 : Create a class which will provide the number to be printed by the the threads. Threads
will share the same instance of this class. We will just provide the starting number to
this class & rest activities will e controlled by this class like how to increment the
number, what message will be printed by each thread and when the execution will stop.
I also say the same.
So you know doing multithreading is not a joke & its tricky to do synchronization among
threads.
To test such knowledge, interviewer can ask -
Print Odd & Even numbers via different threads.
Here the problem seems quite easy and we can quickly decide that we will just create 2
separate threads to print Odd and Even numbers but the challenge comes when we need to
orchestrate this printing, synchronize the excecution of 2 threads.
For this we can have multiple ways but below I am giving 2 such ways & rest you can add in the comments sections.
Way 1 : Create a class which will provide the number to be printed by the the threads. Threads
will share the same instance of this class. We will just provide the starting number to
this class & rest activities will e controlled by this class like how to increment the
number, what message will be printed by each thread and when the execution will stop.
Odd Even : Way 1
Way 2 : For some cases, above way will be fine but many times, you would want to have control the number increment, its range & what message to be printed or what condition will be processed by which thread, not only about even or odd.
So below way, we can control what numbers we want to process, on what condition one
thread should process the number, what message to print & when you want to stop execution.
If you see, below way also seems bit simple. Also you can start similar or different threads depending upon the requirements.
So below way, we can control what numbers we want to process, on what condition one
thread should process the number, what message to print & when you want to stop execution.
If you see, below way also seems bit simple. Also you can start similar or different threads depending upon the requirements.
Odd Even : Way 2
Below code will execute both the above ways--
Main method