美文网首页
多线程-打印零与奇偶数的3种写法

多线程-打印零与奇偶数的3种写法

作者: 97_灰太狼 | 来源:发表于2020-02-18 18:33 被阅读0次
    class ZeroEvenOdd {
      public ZeroEvenOdd(int n) { ... }      // 构造函数
      public void zero(printNumber) { ... }  // 仅打印出 0
      public void even(printNumber) { ... }  // 仅打印出 偶数
      public void odd(printNumber) { ... }   // 仅打印出 奇数
    }
    相同的一个 ZeroEvenOdd 类实例将会传递给三个不同的线程:
    
    线程 A 将调用 zero(),它只输出 0 。
    线程 B 将调用 even(),它只输出偶数。
    线程 C 将调用 odd(),它只输出奇数。
    每个线程都有一个 printNumber 方法来输出一个整数。请修改给出的代码以输出整数序列 010203040506... ,其中序列的长度必须为 2n。
    
    示例 1:
    
    输入:n = 2
    输出:"0102"
    说明:三条线程异步执行,其中一个调用 zero(),另一个线程调用 even(),最后一个线程调用odd()。正确的输出为 "0102"。
    示例 2:
    
    输入:n = 5
    输出:"0102030405"
    
    

    写法1:使用volatile的可见性,让变量来控制,Thread.yield()使线程让出当前时间片给其他线程执行。

    public class ZeroEvenOdd {
        //定义flag,为0代表执行zero,为1代表执行odd(奇数),为2代表执行even(偶数)
         private volatile int flag = 0;
    
        private int n;
    
        public ZeroEvenOdd(int n) {
            this.n = n;
        }
    
        // printNumber.accept(x) outputs "x", where x is an integer.
        public void zero(IntConsumer printNumber) throws InterruptedException {
            for (int i = 0; i < n; i++) {
                while (flag != 0){
                    Thread.yield();
                }
                printNumber.accept(0);
                if (i % 2 != 0){
                    flag = 2;
                }else {
                    flag = 1;
                }
    
            }
    
        }
    
        public void even(IntConsumer printNumber) throws InterruptedException {
            for (int i = 2; i <= n; i=i+2) {
                while (flag != 2){
                    Thread.yield();
                }
                printNumber.accept(i);
                flag = 0;
            }
        }
    
        public void odd(IntConsumer printNumber) throws InterruptedException {
            for (int i = 1; i <= n; i=i+2) {
                while (flag != 1){
                    Thread.yield();
                }
                printNumber.accept(i);
                flag = 0;
            }
    
    
        }
    }
    
    

    写法2:使用信号量Semaphore,先获取许可证,再执行。

    public class ZeroEvenOdd {
       
        private  Semaphore z = new Semaphore(1);
         private  Semaphore e = new Semaphore(0);
          private  Semaphore o = new Semaphore(0);
    
        private int n;
    
        public ZeroEvenOdd(int n) {
            this.n = n;
        }
    
        // printNumber.accept(x) outputs "x", where x is an integer.
        public void zero(IntConsumer printNumber) throws InterruptedException {
           for(int i = 0; i < n; i++){
              z.acquire();
               printNumber.accept(0);
               if(i % 2 == 0){
                   o.release();
               } else {
                   e.release();
               }
           }
    
        }
    
        public void even(IntConsumer printNumber) throws InterruptedException {
            for(int i = 2; i <= n; i+=2){
                e.acquire();
                 printNumber.accept(i);
                 z.release();
            }
           
        }
    
        public void odd(IntConsumer printNumber) throws InterruptedException {
           
            for(int i = 1; i <= n; i+=2){
               o.acquire();
                printNumber.accept(i);
               z.release();
            }
    
        }
    }
    

    写法3:加锁

    public class ZeroEvenOdd {
       
       private volatile int flag = 0;
    
       private Lock lock = new ReentrantLock();
        private Condition z = lock.newCondition();
        private Condition e = lock.newCondition();
        private Condition o = lock.newCondition();
    
    
    
        private int n;
    
        public ZeroEvenOdd(int n) {
            this.n = n;
        }
    
        // printNumber.accept(x) outputs "x", where x is an integer.
        public void zero(IntConsumer printNumber) throws InterruptedException {
            lock.lock();
            try{
            for(int i = 0; i < n; i++){
             while(flag != 0){
                 z.await();
             }
               printNumber.accept(0);
               if(i % 2 == 0){
                   flag = 1;
                   o.signal();
               } else {
                   flag = 2;
                   e.signal();
               }
                z.await();
           }
            } finally{
                lock.unlock();
            }
           
    
        }
    
        public void even(IntConsumer printNumber) throws InterruptedException {
             lock.lock();
            try{
                 for(int i = 2; i <= n; i+=2){
               while(flag != 2){
                   e.await();
               }
                 printNumber.accept(i);
                 flag = 0;
                 z.signal();
            }
            }
            finally{
                lock.unlock();
            }
        
           
        }
    
        public void odd(IntConsumer printNumber) throws InterruptedException {
            lock.lock();
            try{
            for(int i = 1; i <= n; i+=2){
               while(flag != 1){
                   o.await();
               };
                printNumber.accept(i);
                flag = 0;
               z.signal();
            }
            } finally{
                lock.unlock();
            }
            
    
        }
    }
    

    个人座右铭:主动 行动 思考 反省 总结

    相关文章

      网友评论

          本文标题:多线程-打印零与奇偶数的3种写法

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