Java|java线程,顺序打印abc

遇到过一个面试题,按顺序打印abc,输出十次,先说下解题思路,当打印a后,打印a和打印c的程序不能执行,只有打印b的程序可以执行,以此类推,就可以轻松解答了。
【Java|java线程,顺序打印abc】runnable实现如下:

class SortRunnable implements Runnable{private String value; private final Object prev; private final Object self; SortRunnable(String value, Object prev, Object self) { this.value = https://www.it610.com/article/value; this.prev = prev; this.self = self; }@Override public void run() { int count = 10; while (count> 0) { synchronized (prev) { synchronized (self) { System.out.print(value); count--; self.notify(); } try { // 如果这里不设置超时时间,程序将进入死锁,不会停止 prev.wait(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }

调用方法:
public class Main { public static void main(String[] args) { String a = "a"; String b = "b"; String c = "c"; SortRunnable a1 = new SortRunnable("A", c, a); SortRunnable b1 = new SortRunnable("B", a, b); SortRunnable c1 = new SortRunnable("C", b, c); new Thread(a1).start(); new Thread(b1).start(); new Thread(c1).start(); } }

输出结果:
ABCABCABCABCABCABCABCABCABCABC

这里备一个planB:
public class Main {private static Boolean isThreadA = true; private static Boolean isThreadB = false; private static Boolean isThreadC = false; public static void main(String[] args) { final Main obj = new Main(); new Thread(() -> { for (int i = 0; i < 10; i++) { synchronized (obj) { while(!isThreadA) { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print("A"); isThreadA = false; isThreadB = true; isThreadC = false; obj.notifyAll(); } } }).start(); new Thread(() -> { for (int i = 0; i < 10; i++) { synchronized (obj) { while(!isThreadB) { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print("B"); isThreadA = false; isThreadB = false; isThreadC = true; obj.notifyAll(); } } }).start(); new Thread(() -> { for (int i = 0; i < 10; i++) { synchronized (obj) { while(!isThreadC) { try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print("C"); isThreadA = true; isThreadB = false; isThreadC = false; obj.notifyAll(); } } }).start(); } }

    推荐阅读