解法一
package com.qianfeng.yxl.the19.example;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* lenovo 2019/8/11 13:54
*/
public class ABC {
private static final int COUNT = 20 * 3;//20是每个字母输出20遍
private static int state = 1; // 3是有3个字母交替输出,COUNT是总共输出的遍数
public static void main(String[] args) {
final Lock l = new ReentrantLock();
Thread A = new Thread(new Runnable(){
@Override
public void run() {
while (state <= COUNT) {
l.lock();
if(state <= COUNT && state%3==1){
System.out.println(Thread.currentThread().getName() + "线程->" + state + "A");
state ++;
}
l.unlock();
}
}
},"A");
Thread B = new Thread(new Runnable(){
@Override
public void run() {
while (state <= COUNT) {
l.lock();
if(state <= COUNT && state%3==2){
System.out.println(Thread.currentThread().getName() + "线程->" + state + "B");
state ++;
}
l.unlock();
}
}
},"B");
Thread C = new Thread(new Runnable(){
@Override
public void run() {
while (state <= COUNT) {
l.lock();
if(state <= COUNT && state%3==0){
System.out.println(Thread.currentThread().getName() + "线程->" + state + "C");
state++;
}
l.unlock();
}
}
},"C");
A.start();
B.start();
C.start();
}
}
解法二
/**
* lenovo 2019/8/14 15:19
*/
public class AlternativePrint {
private Lock lock = new ReentrantLock();
Condition conditionA = lock.newCondition();
Condition conditionB = lock.newCondition();
Condition conditionC = lock.newCondition();
private int num = 1;
private int count = 1;
public void printA() throws InterruptedException {
lock.lock();
try {
if(num != 1){
conditionA.await();
}
System.out.println("A");
num = 2;
conditionB.signal();
}finally {
lock.unlock();
}
}
public void printB() throws InterruptedException {
lock.lock();
try {
if(num != 2){
conditionB.await();
}
System.out.println("B");
num = 3;
conditionC.signal();
}finally {
lock.unlock();
}
}
public void printC() throws InterruptedException {
lock.lock();
try {
if(num != 3){
conditionC.await();
}
System.out.println("C");
System.out.println("------"+count+"------");
count++;
num = 1;
conditionA.signal();
}finally {
lock.unlock();
}
}
}
/**
* lenovo 2019/8/14 15:24
*/
public class Test {
public static void main(String[] args) {
AlternativePrint alternative = new AlternativePrint();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i < 20;i++){
try {
alternative.printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i < 20;i++){
try {
alternative.printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i < 20;i++){
try {
alternative.printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}