编写一个可以从 1 到 n 输出代表这个数字的字符串的程序,但是:
如果这个数字可以被 3 整除,输出 “fizz”。
如果这个数字可以被 5 整除,输出 “buzz”。
如果这个数字可以同时被 3 和 5 整除,输出 “fizzbuzz”。
例如,当 n = 15,输出: 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizzbuzz。
来源:力扣(LeetCode)
采用信号量Semaphore进行线程控制,但是调试了半天总是不通过,一直提示超时,看了下通过的答案和我的设计是一样的,于是复制粘贴了一下发现竟然通过了。仔细看了一下,发现竟然是try-finally块没写就造成通不过了。finally块保证了线程一定会释放信号量。
class FizzBuzz {
private int n;
private volatile int cnt;
private Semaphore semaphore=null;
public FizzBuzz(int n) {
this.n = n;
cnt=1;
semaphore=new Semaphore(1);
}
// printFizz.run() outputs "fizz".
public void fizz(Runnable printFizz) throws InterruptedException {
while(true){
try{
semaphore.acquire();
if(cnt>n){
return;
}
if(cnt%3==0&&cnt%5!=0){
printFizz.run();
cnt++;
}
}finally{
semaphore.release();
}
}
}
// printBuzz.run() outputs "buzz".
public void buzz(Runnable printBuzz) throws InterruptedException {
while(true){
try{
semaphore.acquire();
if(cnt>n){
return;
}
if(cnt%3!=0&&cnt%5==0){
printBuzz.run();
cnt++;
}
}finally{
semaphore.release();
}
}
}
// printFizzBuzz.run() outputs "fizzbuzz".
public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
while(true){
try{
semaphore.acquire();
if(cnt>n){
return;
}
if(cnt%3==0&&cnt%5==0){
printFizzBuzz.run();
cnt++;
}
}finally{
semaphore.release();
}
}
}
// printNumber.accept(x) outputs "x", where x is an integer.
public void number(IntConsumer printNumber) throws InterruptedException {
while(true){
try{
semaphore.acquire();
if(cnt>n){
return;
}
if(cnt%3!=0&&cnt%5!=0){
printNumber.accept(cnt);
cnt++;
}
}finally{
semaphore.release();
}
}
}
}