使用ReentrantLock和Condition实现
public static class ABC_Runnable implements Runnable {
private final char word;
private final Lock lock;
private final Condition currentCondition;
private ABC_Runnable nextRunnable;
private boolean runSwitch = false ;
public ABC_Runnable ( char word, Lock lock) {
this . word = word;
this . lock = lock;
this . currentCondition = lock. newCondition ( ) ;
}
@Override
public void run ( ) {
try {
lock. lock ( ) ;
for ( int i = 0 ; i < 10 ; i++ ) {
while ( ! runSwitch) {
currentCondition. await ( ) ;
}
System . out. print ( word) ;
runSwitch = false ;
waitNextRunnable ( ) ;
}
} catch ( Exception e) {
e. printStackTrace ( ) ;
} finally {
lock. unlock ( ) ;
}
}
private void waitNextRunnable ( ) {
nextRunnable. runSwitch = true ;
nextRunnable. currentCondition. signal ( ) ;
}
public void setNextRunnable ( ABC_Runnable nextRunnable) {
this . nextRunnable = nextRunnable;
}
}
public static void main ( String [ ] args) {
Lock lock = new ReentrantLock ( ) ;
ABC_Runnable a = new ABC_Runnable ( 'A' , lock) ;
ABC_Runnable b = new ABC_Runnable ( 'B' , lock) ;
ABC_Runnable c = new ABC_Runnable ( 'C' , lock) ;
a. setNextRunnable ( b) ;
b. setNextRunnable ( c) ;
c. setNextRunnable ( a) ;
a. runSwitch = true ;
ExecutorService executorService = Executors . newFixedThreadPool ( 3 ) ;
executorService. submit ( a) ;
executorService. submit ( b) ;
executorService. submit ( c) ;
}