Title: There are a,b,c three threads, a thread output A, b thread output B, c thread output C, request, simultaneously start three threads, sequentially output ABC, loop 10 times.
Problem-solving ideas: to sequentially output ABC, loop 10 times, it is necessary to control three threads synchronous work, that is, to let three threads in turn output, until 10 ABC all output will end the thread. Here, a lock object is used to control the synchronization of three threads. A variable of type int is used to identify the output by that thread.
ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classPRINTABC { Public Static intCNT = 0; Public Static Final intCOUNT = 30; Public Static voidMain (string[] args) {FinalLock lock =NewReentrantlock (); Thread A=NewThread (NewRunnable () {@Override Public voidrun () { while(true) {lock.lock (); if(cnt>=COUNT) {Lock.unlock (); return; } if(cnt%3==0) {System.out.println (A); CNT++; } lock.unlock (); } } }); Thread B=NewThread (NewRunnable () { Public voidrun () { while(true) {lock.lock (); if(cnt>=COUNT) {Lock.unlock (); return; } if(cnt%3==1) {System.out.println (B); CNT++; } lock.unlock (); } } }); Thread C=NewThread (NewRunnable () { Public voidrun () { while(true) {lock.lock (); if(cnt>=COUNT) {Lock.unlock (); return; } if(cnt%3==2) {System.out.println (C); CNT++; } lock.unlock (); } } }); A.start (); B.start (); C.start (); }}
The results of the program run as follows:
Abcabcabcabcabcabcabcabcabcabc
Java Multithreading: Using three threads to control the loop output 10 times ABC