java">public class Test9 {
static Object lock = new Object ( ) ;
static int num = 1 ;
static int loopNum = 5 ;
public static void main ( String [ ] args) throws InterruptedException {
Thread t1 = new Thread ( ( ) -> {
f ( 1 , 2 , "a" ) ;
} , "t1" ) ;
Thread t2 = new Thread ( ( ) -> {
f ( 2 , 3 , "b" ) ;
} , "t2" ) ;
Thread t3 = new Thread ( ( ) -> {
f ( 3 , 1 , "c" ) ;
} , "t3" ) ;
t1. start ( ) ;
t2. start ( ) ;
t3. start ( ) ;
}
private static void f ( int current, int next, String word) {
for ( int i = 0 ; i < loopNum; i ++ ) {
synchronized ( lock) {
while ( current != num) {
try {
lock. wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System . out. print ( word) ;
num = next;
lock. notifyAll ( ) ;
}
}
}
}
java">public class Test10 {
static ReentrantLock lock = new ReentrantLock ( ) ;
static Condition a = lock. newCondition ( ) ;
static Condition b = lock. newCondition ( ) ;
static Condition c = lock. newCondition ( ) ;
static int loopNum = 5 ;
public static void main ( String [ ] args) throws InterruptedException {
Thread t1 = new Thread ( ( ) -> {
f ( a, b, "a" ) ;
} , "t1" ) ;
Thread t2 = new Thread ( ( ) -> {
f ( b, c, "b" ) ;
} , "t2" ) ;
Thread t3 = new Thread ( ( ) -> {
f ( c, a, "c" ) ;
} , "t3" ) ;
t1. start ( ) ;
t2. start ( ) ;
t3. start ( ) ;
Thread . sleep ( 1000 ) ;
lock. lock ( ) ;
try {
System . out. println ( "开始..." ) ;
a. signal ( ) ;
} finally {
lock. unlock ( ) ;
}
}
private static void f ( Condition current, Condition next, String word) {
for ( int i = 0 ; i < loopNum; i++ ) {
lock. lock ( ) ;
try {
current. await ( ) ;
System . out. print ( word) ;
next. signal ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
} finally {
lock. unlock ( ) ;
}
}
}
}
java">public class Test11 {
static ReentrantLock lock = new ReentrantLock ( ) ;
static Thread t1;
static Thread t2;
static Thread t3;
static int loopNum = 5 ;
public static void main ( String [ ] args) throws InterruptedException {
t1 = new Thread ( ( ) -> {
f ( t2, "a" ) ;
} , "t1" ) ;
t2 = new Thread ( ( ) -> {
f ( t3, "b" ) ;
} , "t2" ) ;
t3 = new Thread ( ( ) -> {
f ( t1, "c" ) ;
} , "t3" ) ;
t1. start ( ) ;
t2. start ( ) ;
t3. start ( ) ;
Thread . sleep ( 1000 ) ;
LockSupport . unpark ( t1) ;
}
private static void f ( Thread next, String word) {
for ( int i = 0 ; i < loopNum; i ++ ) {
LockSupport . park ( ) ;
System . out. print ( word) ;
LockSupport . unpark ( next) ;
}
}
}