美文网首页
java刷题-3

java刷题-3

作者: robertzhai | 来源:发表于2022-08-14 07:43 被阅读0次

    总结

    用一个变量来控制流转

    1、https://leetcode.cn/problems/fizz-buzz-multithreaded/submissions/

    class FizzBuzz {
    
        private int n;
    
        private volatile int printType ;// 0 3 5 15 
    
    
        public FizzBuzz(int n) {
            this.n = n;
            printType = 0;
    
        }
    
        // printFizz.run() outputs "fizz".
        public void fizz(Runnable printFizz) throws InterruptedException {
           
            for(int i=3;i<=n;i+=3) {
                if(i%15 == 0) {
                    continue;
                }
                while(printType != 3) {
                    Thread.yield();
                }
                printFizz.run();
                printType = 0;
                
            }
            
        }
    
        // printBuzz.run() outputs "buzz".
        public void buzz(Runnable printBuzz) throws InterruptedException {
    
              for(int i=5;i<=n;i+=5) {
    
                if(i%15 == 0) {
                    continue;
                }
                while(printType != 5) {
                    Thread.yield();
                }
                
                printBuzz.run();
                printType = 0;
                
            }
            
             
            
        }
    
        // printFizzBuzz.run() outputs "fizzbuzz".
        public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
            for(int i=15;i<=n;i+=15) {
                while(printType != 15) {
                    Thread.yield();
                }
                printFizzBuzz.run();
                printType = 0;
                
            }
            
            
        }
    
        // printNumber.accept(x) outputs "x", where x is an integer.
        public void number(IntConsumer printNumber) throws InterruptedException {
    
            for(int i = 1; i<=n; i++) {
                 while(printType != 0) {
                    Thread.yield();
                }
                if (i%15== 0) {
                     printType = 15;
                } else if (i%3 == 0) {
                    printType = 3;
                } else if (i%5==0) {
                     printType = 5;
                } else {
                    printNumber.accept(i);
                }
            }
            
        }
    }
    
    

    相关文章

      网友评论

          本文标题:java刷题-3

          本文链接:https://www.haomeiwen.com/subject/ldxcgrtx.html