Java代码实现按序打印(多线程)

  • Post author:
  • Post category:java


使用synchronized关键字同步线程,线程会在while循环中等待条件满足。如果当前要打印的数字为1,则打印1,并将当前要打印的数字设置为2。最后,调用notifyAll()方法唤醒所有正在等待的线程,让它们继续执行。

class PrintSequence {
    private int current = 1;// 当前要打印的数字,初始为1
    private Object lock = new Object();// 定义一个用于同步线程的锁对象

    void printFirst() {
        synchronized (lock) {// 线程同步
            while (current != 1) {// 条件不满足时等待
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(1);// 打印1
            current = 2;// 设置下一个要打印的数字
            lock.notifyAll();// 唤醒其他正在等待的线程
        }
    }

    void printSecond() {
        synchronized (lock) {
            while (current != 2) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(2);
            current = 3;
            lock.notifyAll();
        }
    }

    void printThird() {
        synchronized (lock) {
            while (current != 3) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(3);
            current = 1;
            lock.notifyAll();
        }
    }

    public static void main(String[] args) {
        PrintSequence ps = new PrintSequence();// 创建PrintSequence对象
        new Thread(() -> { // 创建一个线程,调用printFirst()方法打印数字1
            for (int i = 0; i < 33; i++) {
                ps.printFirst();
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 33; i++) {
                ps.printSecond();
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 33; i++) {
                ps.printThird();
            }
        }).start();
    }
}



版权声明:本文为qq_45450889原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。