Android面试题|两个线程分别持续打印奇数和偶数,实现两个线程的交替打印(从小到大)

public class OddEvenPrinter {private static final int MAX_NUMBER = 20; private static final Object monitor = new Object(); private static int value = https://www.it610.com/article/1; public static void main(String[] args) {PrintRunnable printRunnable = new PrintRunnable(); new Thread(printRunnable).start(); new Thread(printRunnable).start(); }static class PrintRunnable implements Runnable {@Override public void run() { synchronized (monitor) { while (value <= MAX_NUMBER) { try { System.out.println(Thread.currentThread().getName() +":" + value++); monitor.notify(); monitor.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }} }}

【Android面试题|两个线程分别持续打印奇数和偶数,实现两个线程的交替打印(从小到大)】运行结果:
Thread-0:1 Thread-1:2 Thread-0:3 Thread-1:4 Thread-0:5 Thread-1:6 Thread-0:7 Thread-1:8 Thread-0:9 Thread-1:10 Thread-0:11 Thread-1:12 Thread-0:13 Thread-1:14 Thread-0:15 Thread-1:16 Thread-0:17 Thread-1:18 Thread-0:19 Thread-1:20

    推荐阅读