美文网首页
一道线程面试题

一道线程面试题

作者: cjxll | 来源:发表于2019-06-19 18:38 被阅读0次

    2个线程交替打印1-100内的数,线程A打印偶数,线程B打印奇数

    打印结果如下:

    A: 0
    B: 1
    A: 2
    B: 3
    A: 4
    B: 5
    ......
    

    实现代码

    
    public class printNum{
    
        public static void main(String[] args) {
            ThreadPrintNum threadPrintNum = new ThreadPrintNum();
            new Thread(() -> {
                for (int i = 0; i <= 100; i += 2) {
                    threadPrintNum.printEven(i);
                }
            },"A").start();
            new Thread(() -> {
                for (int i = 1; i < 100; i += 2) {
                    threadPrintNum.printOdd(i);
                }
            },"B").start();
        }
    }
    
    class ThreadPrintNum {
        private int num = 1;
    
        private ReentrantLock lock = new ReentrantLock();
        private Condition condition1 = lock.newCondition();
        private Condition condition2 = lock.newCondition();
    
        /**
         * 打印偶数
         * @param i
         */
        public void printEven(int i){
            lock.lock();
            try {
                if(num != 1){
                    condition1.await();
                }
                System.out.println(Thread.currentThread().getName() + ": " + i);
                num = 2;
                condition2.signal();
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    
        /**
         * 打印奇数
         * @param i
         */
        public void printOdd(int i){
            lock.lock();
            try {
                if (num != 2){
                    condition2.await();
                }
                System.out.println(Thread.currentThread().getName() + ": " + i);
                num = 1;
                condition1.signal();
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:一道线程面试题

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