按序打印_lock和condition

时间:2021-08-31
本文章向大家介绍按序打印_lock和condition,主要包括按序打印_lock和condition使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
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();
    }
}

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