-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFizzBuzz.java
More file actions
117 lines (100 loc) · 2.71 KB
/
FizzBuzz.java
File metadata and controls
117 lines (100 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package interview;
public class FizzBuzz {
public static void main(String[] args) {
MultiThreadedFizzbuzz obj = new MultiThreadedFizzbuzz(15);
Thread t1 = new FizzBuzzThread(obj,"Fizz");
Thread t2 = new FizzBuzzThread(obj,"Buzz");
Thread t3 = new FizzBuzzThread(obj,"FizzBuzz");
Thread t4 = new FizzBuzzThread(obj,"Number");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class MultiThreadedFizzbuzz{
private int n;
private int num =1;
public MultiThreadedFizzbuzz(int n){
this.n = n;
}
public synchronized void fizz() throws InterruptedException{
while (num <= n){
if(num % 3 == 0 & num %5 !=0 ){
System.out.println("Fizz!");
num++;
notifyAll();
}else {
wait();
}
}
}
public synchronized void buzz() throws InterruptedException{
while (num <= n){
if(num % 3 != 0 & num %5 ==0 ){
System.out.println("Buzz!");
num++;
notifyAll();
}else {
wait();
}
}
}
public synchronized void fizzbuzz() throws InterruptedException{
while (num <= n){
if(num %15 ==0 ){
System.out.println("FizzBuzz!");
num++;
notifyAll();
}else {
wait();
}
}
}
public synchronized void num() throws InterruptedException{
while (num <= n){
if(num %3 !=0 && num %5 !=0 ){
System.out.println(num);
num++;
notifyAll();
}else {
wait();
}
}
}
}
class FizzBuzzThread extends Thread{
MultiThreadedFizzbuzz obj;
String method;
public FizzBuzzThread(MultiThreadedFizzbuzz obj, String method){
this.obj=obj;
this.method=method;
}
@Override
public void run() {
if("Fizz".equals(method)){
try{
obj.fizz();
}catch (Exception e){
}
}
else if("Buzz".equals(method)){
try{
obj.buzz();
}catch (Exception e){
}
}
else if("FizzBuzz".equals(method)){
try{
obj.fizzbuzz();
}catch (Exception e){
}
}
else if("Number".equals(method)){
try{
obj.num();
}catch (Exception e){
}
}
}
}