一、Lock锁加Condition实现(推荐)
LockABC:
class RunMain {
public static void main(String[] args) {
LockABC lockABC = new LockABC();
new Thread(new Runnable() {
@Override
public void run() {
lockABC.printA();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
lockABC.printB();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
lockABC.printC();
}
}).start();
}
}
public class LockABC {
//Lock锁实现,比较灵活,且比synchronized轻量,推荐
private static final ReentrantLock lock = new ReentrantLock();
private Condition conditionA = lock.newCondition();
private Condition conditionB = lock.newCondition();
private Condition conditionC = lock.newCondition();
//标识位 0-A 1-B 2-C
private int flag = 0;
public void printA() {
lock.lock();
try {
while (true) {
while (flag != 0) {
conditionA.await();//进入等待,释放了锁
}
System.out.println("A");
flag = 1;
conditionB.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB() {
lock.lock();
try {
while (true) {
while (flag != 1) {
conditionB.await();
}
System.out.println("B");
flag = 2;
conditionC.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC() {
lock.lock();
try {
while (true) {
while (flag != 2) {
conditionC.await();
}
System.out.println("C");
flag = 0;
Thread.sleep(1000);
conditionA.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
二、单线程池执行任务,也能顺序打印ABC(记录一下)
public class ThreeThread {
public static void main(String[] args) throws InterruptedException {
//用线程池实现:核心就是SingleThreadExecutor,单线程,队列任务FIFO先进先出
ExecutorService pool = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
pool.submit(() -> System.out.println("A"));
pool.submit(() -> System.out.println("B"));
pool.submit(() -> System.out.println("C"));
}
pool.shutdown();
}
}