-
Notifications
You must be signed in to change notification settings - Fork 0
/
1195.交替打印字符串.java
78 lines (70 loc) · 2.06 KB
/
1195.交替打印字符串.java
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
/*
* @lc app=leetcode.cn id=1195 lang=java
*
* [1195] 交替打印字符串
*/
// @lc code=start
class FizzBuzz {
private int curr = 1;
private int n;
public FizzBuzz(int n) {
this.n = n;
}
// printFizz.run() outputs "fizz".
public void fizz(Runnable printFizz) throws InterruptedException {
while (this.curr <= this.n) {
synchronized(this) {
if (this.curr % 3 == 0 && this.curr % 5 != 0) {
printFizz.run();
this.curr++;
notifyAll();
} else {
wait();
}
}
}
}
// printBuzz.run() outputs "buzz".
public void buzz(Runnable printBuzz) throws InterruptedException {
while (this.curr <= this.n) {
synchronized(this) {
if (this.curr % 3 != 0 && this.curr % 5 == 0) {
printBuzz.run();
this.curr++;
notifyAll();
} else {
wait();
}
}
}
}
// printFizzBuzz.run() outputs "fizzbuzz".
public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
while (this.curr <= this.n) {
synchronized(this) {
if (this.curr % 3 == 0 && this.curr % 5 == 0) {
printFizzBuzz.run();
this.curr++;
notifyAll();
} else {
wait();
}
}
}
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void number(IntConsumer printNumber) throws InterruptedException {
while (this.curr <= this.n) {
synchronized(this) {
if (this.curr % 3 != 0 && this.curr % 5 != 0) {
printNumber.accept(this.curr);
this.curr++;
notifyAll();
} else {
wait();
}
}
}
}
}
// @lc code=end