三个线程按顺序打印分别打印ABC

我只是一个虾纸丫 提交于 2020-03-01 09:33:20

 

 

 

public static Lock lock = new ReentrantLock();
    public static int count = 1;
    public static Condition condition1 = lock.newCondition();
    public static Condition condition2 = lock.newCondition();
    public static Condition condition3 = lock.newCondition();

    public static Thread thread1 = new Thread(() -> {

        while (count < 100) {
            lock.lock();
            System.out.println("A:" + count);
            count ++;
            condition2.signal();
            try {
                condition1.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            lock.unlock();
        }
    });

    public static Thread thread2 = new Thread(() -> {

        while (count < 100) {
            lock.lock();

            System.out.println("B:" + count);
            count ++;
            condition3.signal();
            try {
                condition2.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            lock.unlock();
        }

    });

    public static Thread thread3 = new Thread(() -> {
        while (count < 100) {
            lock.lock();

            System.out.println("C:" + count);
            count ++;
            condition1.signal();
            try {
                condition3.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
        }
    });

    public static void main (String[] args) {
        thread1.start();

        try {
            Thread.sleep(1l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.start();
        try {
            Thread.sleep(1l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread3.start();

    }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!