首页 > 其他 > 详细

按序打印_lock和condition

时间:2021-09-01 14:08:38      阅读:22      评论:0      收藏:0      [点我收藏+]
public class SortedPrintMore extends Thread{
    //由于是不同的Thread  n最好是共享
    //无锁化
    int i;
    static int n;
    static Lock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();
    public SortedPrintMore(int n) {
        this.i = n;
    }
    //使用lock和condition
    @Override
    public void run() {
        while(true){
            if(n %3 == i){
                //抢到锁了
                if(n>100) return;
                lock.lock();
                System.out.println(Thread.currentThread().getName()+" : "+n++);
                try {
                    condition.signalAll();
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        SortedPrintMore more1 = new SortedPrintMore(0);
        SortedPrintMore more2 = new SortedPrintMore(1);
        SortedPrintMore more3 = new SortedPrintMore(2);
        more1.start();
        more2.start();
        more3.start();
    }
}

按序打印_lock和condition

原文:https://www.cnblogs.com/purexww/p/15209763.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!