`CountDownLatch` + `Semaphore `思路清晰
多线程
http://www.nowcoder.com/questionTerminal/cd99fbc6154d4074b4da0e74224a1582
CountDownLatch
+ Semaphore
思路清晰
import java.util.Scanner; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; /** */ public class Main{ public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ final int size = sc.nextInt(); final char[] arr = new char[size * 4]; final CountDownLatch cdl = new CountDownLatch(4); final Semaphore a = new Semaphore(1); final Semaphore b = new Semaphore(0); final Semaphore c = new Semaphore(0); final Semaphore d = new Semaphore(0); new Thread(() -> { for(int i = 0; i < arr.length; i+=4){ try{ a.acquire(); } catch (Exception e){} arr[i] = 'A'; b.release(); } cdl.countDown(); }).start(); new Thread(() -> { for(int i = 1; i < arr.length; i+=4){ try{ b.acquire(); } catch (Exception e){} arr[i] = 'B'; c.release(); } cdl.countDown(); }).start(); new Thread(() -> { for(int i = 2; i < arr.length; i+=4){ try{ c.acquire(); } catch (Exception e){} arr[i] = 'C'; d.release(); } cdl.countDown(); }).start(); new Thread(() -> { for(int i = 3; i < arr.length; i+=4){ try{ d.acquire(); } catch (Exception e){} arr[i] = 'D'; a.release(); } cdl.countDown(); }).start(); cdl.await(); for(char c2 : arr){ System.out.print(c2); } System.out.println(); } } }