多线程循环打印问题的几种解决方案
1. 使用同步锁实现
public class SyncThread {
/**
* 保证第一条执行的线程
*/
static CountDownLatch countDownLatch = new CountDownLatch(1);
public static void main(String[] args) {
final Object o = new Object();
char[] num = "123456".toCharArray();
char[] ab = "qwerty".toCharArray();
new Thread(() -> {
//锁
synchronized (o) {
for (char i : num) {
//先执行的线程
System.out.println(i);
//减少信号量
countDownLatch.countDown();
//唤醒其他线程
o.notify();
try {
//放弃对象锁,进入等待队列
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}