publicclassMain{ privatestaticfinal Semaphore[] s = {new Semaphore(1), new Semaphore(0), new Semaphore(0)}; publicstaticvoidmain(String[] args){ Scanner input = new Scanner(System.in); int n = input.nextInt(); input.close(); new Thread(() -> { try { for (int i = 0; i < n; i++) { s[0].acquire(); System.out.print('A'); s[1].release(); }
} catch (InterruptedException e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { for (int i = 0; i < n; i++) { s[1].acquire(); System.out.print('B'); s[2].release(); } } catch (InterruptedException e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { for (int i = 0; i < n; i++) { s[2].acquire(); System.out.print('C'); s[0].release(); } } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } }
publicstaticvoidmain(String[] args){ Main main = new Main(); new Thread(() -> { for (int i = 0; i < 5; i++) main.printLetter(0, c1, c2, 5); }, "A").start(); new Thread(() -> { for (int i = 0; i < 5; i++) main.printLetter(1, c2, c3, 10); }, "B").start(); new Thread(() -> { for (int i = 0; i < 5; i++) { main.printLetter(2, c3, c1, 15); System.out.print(" | "); } }, "C").start(); }
publicvoidprintLetter(int targetStatus, Condition current, Condition next, int times){ lock.lock(); try { while (status % 3 != targetStatus) { current.await(); } for (int i = 0; i < times; i++) { System.out.print(Thread.currentThread().getName()); } ++status; next.signal(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }