Question: There are three threads A, B, and C. Thread A outputs thread A, thread B Outputs thread B, and thread C Outputs thread C. required. Three threads are started at the same time and output in sequence, loop 10 times.
Solution: to output ABC in sequence and loop for 10 times, it is necessary to control the synchronization of three threads, that is to say, to let three threads output in turn until all 10 ABC outputs end the thread. Here, a Lock object is used to control the synchronization of three threads. Use an int variable state to identify the output by that thread.
state = 0 Lock l = Thread A = Thread( (state<=30 (state%3==0 System.out.println("A" state ++ Thread B = Thread( (state<=30 (state%3==1 System.out.println("B" state ++ Thread C = Thread( (state<=30 (state%3==2 System.out.println("C" state ++ }
Running result:
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C