网上一大堆实现方式,有花式使用CountDownLatch的,有使用CyclicBarrier的,但是都有各种各样的问题,有些根本就不能100%准确完成任务,不多说直接上我认为最稳妥的实现方式。
package com.myday06.demo;
public class A1B2Text {
//锁对象
Object lock = new Object();
//true:打印字母, false:打印数字
volatile boolean sw = true;
//字母打印线程
Thread chracterPrinter = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
while(!sw){//当前应该打印数字,字母打印应该阻塞
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i='A'; i<='Z'; i++){
System.out.print((char)i);
sw = false;
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}
});
//数字打印线程
Thread numberPrinter = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
while(sw){//当前应该打印字母,数字打印应该阻塞
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i=1; i<=26; i++){
System.out.print(i);
sw = true;
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}
});
public void start(){
chracterPrinter.start();
numberPrinter.start();
}
public static void main(String[] args) {
new A1B2Text().start();
}
}