题目
多线程打印
创造两个线程,其中一个输出1-52,另一个输出A-Z。输出格式要求:12A34B56C78D910E1112F1314G1516H1718I1920J2122K2324L2526M2728N2930O3132P3334Q3536R3738S3940T4142U4344V4546W4748X4950Y5152Z。
解题思路
观察规律,每第三位穿插输出英文字母。
一个线程(A)数出数字,一个线程(B)数出字母。
初始化B线程循环中首先阻塞,当A线程每到第三位 让当前线程A睡眠,唤醒B线程执行。
解题代码
package com.cn.demo;
import lombok.SneakyThrows;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;
/**
* @author lance
* @version 1.0
* @description
* @date 2023-03-27 17:28
**/
public class Testone {
public static volatile List<Integer> number = new ArrayList<>(52);
// 是否第三位
public static volatile boolean flag = true;
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i < 53; i++) {
number.add(i);
}
char[] A_z = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
Thread b = new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
for (char c : A_z) {
LockSupport.park();
if (flag) {
System.out.print(c);
}
flag = false;
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
for (int i = 0; i < noThreads; i++) {
String threadName = lstThreads[i].getName();
if (threadName.equals("myTask-A")) {
LockSupport.unpark(lstThreads[i]);
}
}
}
}
});
b.setName("myTask-B");
b.start();
Thread a = new Thread(new Runnable() {
@SneakyThrows
@Override
public void run() {
int p = 1;
for (int i = 0; i < number.size(); i++) {
Integer ele = number.get(i);
if (p == 3) {
p = 1;
flag = true;
} else {
flag = false;
}
if (!flag) {
System.out.print(ele);
if (i + 1 == number.size()) {
System.out.print(ele);
flag = true;
LockSupport.unpark(b);
}
} else {
LockSupport.unpark(b);
LockSupport.park();
System.out.print(ele);
}
p++;
}
}
});
a.setName("myTask-A");
a.start();
}
}