【快手初面】要求3个线程按顺序循环执行,如循环打印A,B,C
【背景】这个题目是当时远程面试时,手写的题目。自己比较惭愧,当时写的并不好,面试完就又好好的完善了下。
一、题意分析
3个线程要按顺序执行,就要通过线程通信去控制这3个线程的执行顺序。
而线程通信的方式就有wait/notify, condition#await, condition#signal等
二、具体代码
1 public class Main { 2 3 private static String lastCompleteStr = "C"; 4 5 public static void main(String[] args) { 6 new Thread(new PrintTask("A", "C")).start(); 7 new Thread(new PrintTask("B", "A")).start(); 8 new Thread(new PrintTask("C", "B")).start(); 9 } 10 11 static class PrintTask implements Runnable { 12 13 private String cur; 14 15 private String waitLastStr; 16 17 public PrintTask(String cur, String waitLastStr) { 18 this.cur = cur; 19 this.waitLastStr = waitLastStr; 20 } 21 22 @Override 23 public void run() { 24 try { 25 while (true) { 26 synchronized (Main.class) { 27 while (!lastCompleteStr.equals(waitLastStr)) { 28 Main.class.wait(); 29 } 30 31 System.out.println(cur); 32 33 lastCompleteStr = cur; 34 35 Main.class.notifyAll(); 36 } 37 } 38 } catch (Exception e ) { 39 e.printStackTrace(); 40 } 41 } 42 } 43 }