两个线程交替打印奇偶数【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();
                    }
                }
            }
        }
    }
}

 

posted @ 2019-02-22 17:10  Roni_i  阅读(630)  评论(0编辑  收藏  举报