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. An int variable state identifies the output by that thread.
1 PackageCom.thread;2 3 ImportJava.util.concurrent.locks.Lock;4 ImportJava.util.concurrent.locks.ReentrantLock;5 6 Public classABC {7 Private Static intState = 0;8 9 Public Static voidMain (string[] args) {Ten FinalLock L =NewReentrantlock (); One AThread A =NewThread (NewRunnable () { - @Override - Public voidrun () { the while(state<=30) { - L.lock (); - if(state%3==0){ -System.out.println ("A"); +State + +; - } + L.unlock (); A } at } - }); -Thread B =NewThread (NewRunnable () { - @Override - Public voidrun () { - while(state<=30) { in L.lock (); - if(state%3==1){ toSystem.out.println ("B"); +State + +; - } the L.unlock (); * } $ }Panax Notoginseng }); -Thread C =NewThread (NewRunnable () { the @Override + Public voidrun () { A while(state<=30) { the L.lock (); + if(state%3==2){ -System.out.println ("C"); $State + +; $ } - L.unlock (); - } the } - });Wuyi A.start (); the B.start (); - C.start (); Wu } - About}
Original URL: http://www.cnblogs.com/liuling/p/2013-9-13-01.html
Java Multithreading: Using three threads to control the loop output 10 times ABC