多个线程交替打印ABC
package 多个线程交替打印ABC ;
import java. util. concurrent. BrokenBarrierException ;
import java. util. concurrent. CyclicBarrier ;
public class ThreadLoopPrint {
private static int sharedCounter = 0 ;
public static void main ( String [ ] args) {
String printStr = "ABC" ;
CyclicBarrier cyclicBarrier = new CyclicBarrier ( 3 , ( ) -> System . out. println ( ) ) ;
Runnable runnable = new Runnable ( ) {
@Override
public void run ( ) {
for ( int i = 0 ; i < printStr. length ( ) ; i++ ) {
synchronized ( this ) {
sharedCounter = sharedCounter > 2 ? 0 : sharedCounter;
System . out. print ( printStr. toCharArray ( ) [ sharedCounter++ ] ) ;
}
try {
cyclicBarrier. await ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
} catch ( BrokenBarrierException e) {
e. printStackTrace ( ) ;
}
}
}
} ;
new Thread ( runnable) . start ( ) ;
new Thread ( runnable) . start ( ) ;
new Thread ( runnable) . start ( ) ;
}
}