主方法
public static void main(String[] args) {
new Thread(()-> {
try {
test6("a",1,2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()-> {
try {
test6("b", 2, 3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()-> {
try {
test6("c", 3, 1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
1.使用synchorined解决
static int totalFlag = 1;
static Object object = new Object();
public static void test5(String inputStr, int nowFlag, int nextFlag) {
synchronized (object) {
for (int i = 0; i < 3; i++) {
while (nowFlag != totalFlag) {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(inputStr);
totalFlag = nextFlag;
object.notifyAll();
if(nowFlag==3){
System.out.println();
}
}
}
}
2.使用ReentrentLock解决
static ReentrantLock reentrantLock = new ReentrantLock();
static Condition aCondition = reentrantLock.newCondition();
static Condition bCondition = reentrantLock.newCondition();
static Condition cCondition = reentrantLock.newCondition();
public static void test6(String inputStr, int nowFlag, int nextFlag) throws InterruptedException {
try {
reentrantLock.lock();
for (int i = 0; i < 3; i++) {
while (nowFlag != totalFlag) {
switch (nowFlag){
case 1:
aCondition.await();
break;
case 2:
bCondition.await();
break;
case 3:
cCondition.await();
break;
}
}
System.out.print(inputStr);
totalFlag = nextFlag;
switch (nowFlag){
case 1:
bCondition.signalAll();
break;
case 2:
cCondition.signalAll();
break;
case 3:
aCondition.signalAll();
break;
}
if(nextFlag==1){
System.out.println();
}
}
} finally {
reentrantLock.unlock();
}
}