zoukankan      html  css  js  c++  java
  • 两个线程交替打印奇偶数【Lock版】

    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class Solution {
    
        private int start = 1;
        /**
         * 对flag的写入虽然加锁保证了线程安全,但由于读取时不是volatile所以可能会读到旧值
         */
        private volatile boolean flag = false;
        /**
         * 重入锁
         */
        private final static Lock LOCK = new ReentrantLock();
        
    
        public static void main(String[] args) {
            long startTime = System.currentTimeMillis();
            Solution s = new Solution();
            Thread t1 = new Thread(new OuNum(s));
            t1.setName("t1");
            Thread t2 = new Thread(new JiNum(s));
            t2.setName("t2");
            t1.start();
            t2.start();
            long endTime = System.currentTimeMillis();    //获取结束时间
            System.out.println("程序运行时间:" + (endTime - startTime) + "ms");    //输出程序运行时间
        }
    
    
    
        public static class OuNum implements Runnable {
            private Solution number;
            
            public OuNum(Solution number) {
                this.number = number;
            }
    
            @Override
            public void run() {
                while(number.start <= 100) {
                    if(number.flag) {
                        try {
                            LOCK.lock();
                            System.out.println("偶数" + "+-+" + number.start);
                            number.start++;
                            number.flag = false;
                        }finally {
                            LOCK.unlock();
                        }
                    }
                }
            }
            
        }
        
        public static class JiNum implements Runnable {
    
            private Solution number;
            
            public JiNum(Solution number) {
                this.number = number;
            }
    
            @Override
            public void run() {
                while(number.start < 100) {
                    if(!number.flag) {
                        try {
                            LOCK.lock();
                            System.out.println("奇数" + "+-+" + number.start);
                            number.start++;
                            number.flag = true;
                        }finally {
                            LOCK.unlock();
                        }
                    }
                }
            }
        }
    }
  • 相关阅读:
    git提交代码到github步骤
    HTML前端标签
    16-类视图
    15-auth系统与类视图
    14-中间件和上下文处理器
    13-会话技术及表单(cookies和session)
    07-Python Django view 两种return 方法
    10-请求与响应和HTML中的from表单
    09-表关联对象及多表查询
    08-常用查询及表关系的实现
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10419503.html
Copyright © 2011-2022 走看看