1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import java.util.Scanner;
public class PrintABCD { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); startPrintABCD(n); } }
public static void startPrintABCD(int n) { sb = new StringBuffer(); Object a = new Object(); Object b = new Object(); Object c = new Object(); Object d = new Object(); Thread t1 = new Thread(new Task(n, a, b, 'A', 0)); Thread t2 = new Thread(new Task(n, b, c, 'B', 1)); Thread t3 = new Thread(new Task(n, c, d, 'C', 2)); Thread t4 = new Thread(new Task(n, d, a, 'D', 3)); t1.start(); t2.start(); t3.start(); t4.start(); try { t1.join(); t2.join(); t3.join(); t4.join(); System.out.println(sb.toString()); } catch (InterruptedException e) { e.printStackTrace(); } }
private static StringBuffer sb;
static class Task implements Runnable { int n; Object self, target; char ch; int id;
public Task(int n, Object self, Object target, char ch, int id) { this.n = n; this.self = self; this.target = target; this.ch = ch; this.id = id; }
@Override public void run() { while (n-- > 0) { synchronized (self) { while (sb.length() % 4 != id) { waitSelf(); } sb.append(ch); notifyTarget(); waitSelf(); } } notifyTarget(); }
private void waitSelf() { try { self.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
private void notifyTarget() { synchronized (target) { target.notify(); } } } }
|