控制三个线程交替打印ABC

package me.zyc.thread.test;

import java.util.concurrent.locks.AbstractQueuedSynchronizer.ConditionObject;
import java.util.concurrent.locks.ReentrantLock;

public class LoopRunByOrder {
    private static ReentrantLock lock = new ReentrantLock();
    private static String flag = "A";
    private static ConditionObject conditionA = (ConditionObject) lock.newCondition();
    private static ConditionObject conditionB = (ConditionObject) lock.newCondition();
    private static ConditionObject conditionC = (ConditionObject) lock.newCondition();


    public static void main(String[] args) throws InterruptedException {
        new Thread(new TaskA(), "ThreadA").start();
        new Thread(new TaskB(), "ThreadB").start();
        new Thread(new TaskC(), "ThreadC").start();
    }

    static class TaskA implements Runnable{
        @Override
        public void run() {
            int i = 5;
            while(i-- > 0){
                lock.lock();
                try {
                    if(!flag.equals("A")){
                        conditionA.await();
                    }
                    System.out.println("A");
                    flag = "B";
                    conditionB.signal();
                } catch (Exception e) {
                    // TODO: handle exception
                } finally{
                    lock.unlock();
                }
            }
        }
    }

    static class TaskB implements Runnable{
        @Override
        public void run() {
            int i = 5;
            while(i-- > 0){
                lock.lock();
                try {
                    if(!flag.equals("B")){
                        conditionB.await();
                    }
                    System.out.println("B");
                    flag = "C";
                    conditionC.signal();
                } catch (Exception e) {
                    // TODO: handle exception
                } finally{
                    lock.unlock();
                }
            }
        }
    }

    static class TaskC implements Runnable{
        @Override
        public void run() {
            int i = 5;
            while(i-- > 0){
                lock.lock();
                try {
                    if(!flag.equals("C")){
                        conditionC.await();
                    }
                    System.out.println("C");
                    flag = "A";
                    conditionA.signal();
                } catch (Exception e) {
                    // TODO: handle exception
                } finally{
                    lock.unlock();
                }
            }
        }

    }

}

运行结果
控制三个线程交替打印ABC_第1张图片

你可能感兴趣的:(并发,多线程,锁,java)