Java multithreaded application loop output ABC
There are three thread IDs: A, B, and C. Please use multi-line programming to implement it. Print ABCABC 10 times on the screen.
Please add the following code
public class Test { public static void main(String[] args) { MajusculeABC maj = new MajusculeABC(); Thread t_a = new Thread(new Thread_ABC(maj , 'A')); Thread t_b = new Thread(new Thread_ABC(maj , 'B')); Thread t_c = new Thread(new Thread_ABC(maj , 'C')); t_a.start(); t_b.start(); t_c.start(); } } class MajusculeABC { Please add code } class Thread_ABC implements Runnable { Please add code }
The answer is as follows
public class ThreadTest { public static void main(String[] args) throws InterruptedException { MajusculeABC maj = new MajusculeABC(); Thread t_a = new Thread(new Thread_ABC(maj , 'A')); Thread t_b = new Thread(new Thread_ABC(maj , 'B')); Thread t_c = new Thread(new Thread_ABC(maj , 'C')); t_a.start(); t_b.start(); t_c.start(); } private static class MajusculeABC { // Please add the code public MajusculeABC() { } private int a = 1; private synchronized void print(int index, char s) throws InterruptedException { do { if (s == 'A' && a == 1) { a++; (index+"---" + s); notifyAll(); break; } else if (s == 'B' && a == 2) { a++; (index+"---" + s); notifyAll(); break; } else if (s == 'C' && a == 3) { a = 1; (index+"---" + s); notifyAll(); break; } else { wait(); } } while (true); } } private static class Thread_ABC implements Runnable { private char s; private MajusculeABC majusculeABC; // Please add the code public Thread_ABC(MajusculeABC majusculeABC, char s) { = majusculeABC; = s; } @Override public void run() { for (int i = 0; i < 10; i++) { try { (i, s); } catch (InterruptedException e) { (); } } } } }
The output is as follows:
0---A
0---B
0---C
1---A
1---B
1---C
2---A
2---B
2---C
3---A
3---B
3---C
4---A
4---B
4---C
5---A
5---B
5---C
6---A
6---B
6---C
7---A
7---B
7---C
8---A
8---B
8---C
9---A
9---B
9---C
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.