In the previous blogs, We learned  Print Odd Even Numbers Using two threads and  Print 1,2,3 Using 3 Threads with thread synchronization. This is my third blog on the same topic with more code examples and more threads.

Without further ado let’s start the part 2 of this series on Multi-threading where we discuss with actual working examples rather than going through only theory.

## Fizz-Buzz Problem with four threads

### Problem Statement

Implement Fizz buzz program using four threads. The program is supposed to work like this.
1. Print Fizz if divisible by 3 with first thread.
2. Print Buzz if divisible by 5 with second thread.
3. Print Fizz-Buzz if divisible by both with third thread
4. Print just the number if none of the above applies with fourth thread.

I have already established a pattern to solve the problem in my previous blogs. If you are still not able to find it, don’t worry — just hold still you will find it by the end of this post.

### Approach

We need to use four threads here. First one prints Fizz if divisible by 3. Second thread prints Buzz if divisible by 5. Third Thread Prints Fizz-Buzz if divisible by both 3 and 5. Fourth Thread will just print the number if none of the above holds true.

Here, all the threads have a shared access to the Object task which will be accessed by one of the threads at any point of time. The isTurn variable will define which thread should obtain the monitor to task object to print the corresponding message.

Here, we will give thread four a head start. Note here that the task object is shared among all the threads. The variable, isTurn is used to tell which thread should print next based on the next number is defined by getNextNum(int n) method.

First, thread four will print 1 and then next as 2 is not divisible by 3 or 5, thread four will print 2. Next, when number is 3 the first thread will get access and will print Fizz. The same pattern is repeated till 25 which is our limit here.

The output will look like this.

# A bit on volatile Keyword

Let’s assume two or more threads have access to a shared object. If each thread runs on a different processor, they may have their own local copy of the variable in the shared object. Hence, the changes in one thread are not visible to the other.

You know what happens next to our code, if isTurn field is updated in one thread but not visible to other threads.

With the use of volatile keyword, the the changes in one thread are visible to other. More detailed explanation about volatile keyword can be found here and here.