使用ReentrantLock和Condition实现线程顺序执行

直接上代码

public class Test {

    volatile private static int nextOne = 1;
    private static ReentrantLock lock = new ReentrantLock();
    private static Condition c1 = lock.newCondition();
    private static Condition c2 = lock.newCondition();
    private static Condition c3 = lock.newCondition();
    public static void main(String[] args) {
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    while (nextOne != 1){
                        c1.await();
                    }
                    System.out.println("A");
                    nextOne = 2;
                    c2.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    while (nextOne != 2){
                        c2.await();
                    }
                    System.out.println("B");
                    nextOne = 3;
                    c3.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    while (nextOne != 3){
                        c3.await();
                    }
                    System.out.println("C");
                    nextOne = 1;
                    c1.signalAll();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        });

        for(int i = 0; i < 5; i ++){
            Thread t1 = new Thread(threadA);
            Thread t2 = new Thread(threadB);
            Thread t3 = new Thread(threadC);
            t1.start();
            t2.start();
            t3.start();
        }
    }

}

总结

1、利用一个volatile修饰的变量作线程顺序控制
2、利用不同的Condition对象实现当一个线程结束后,唤醒下一个线程

你可能感兴趣的:(使用ReentrantLock和Condition实现线程顺序执行)