下文笔者讲述使用java交替打印输出奇数和偶数的方法分享,如下所示
实现思路: 当打印一个数字后,则wait掉此线程 等打印其它线程运行例:
private int count = 0; private final Object lock = new Object(); @Test public void testMethod() throws InterruptedException { Thread even = new Thread(() -> { System.out.println("偶数开始: " + "******"); while (count <= 100) { synchronized (lock) { System.out.println("偶数: " + count++); lock.notifyAll(); System.out.println("偶数判断: " + "******"); try { // 如果还没有结束,则让出当前的锁并休眠 if (count <= 100) { System.out.println("偶数: " + "开始等待******"); lock.wait(); System.out.println("偶数: " + "等待结束******"); } } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("偶数: " + "end"); }); Thread odd = new Thread(() -> { System.out.println("奇数开始: " + "******"); while (count <= 100) { synchronized (lock) { System.out.println("奇数: " + count++); lock.notifyAll(); System.out.println("奇数判断: " + "******"); try { // 如果还没有结束,则让出当前的锁并休眠 if (count <= 100) { System.out.println("奇数: " + "开始等待******"); lock.wait(); System.out.println("奇数: " + "等待结束******"); } } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("奇数: " + "end"); }); System.out.println("多线程开始: " + "启动even线程"); even.start(); // 确保偶数线程线先获取到锁 System.out.println("多线程: " + "sleep 1秒"); Thread.sleep(1); System.out.println("多线程开始: " + "启动odd线程"); odd.start(); }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。