1、问题:Java实现使用 3 个线程 a,b,c 实现轮流交替输出字符串的每个字符,并显示行号。
2、代码实现(线程池方式)
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Code4 {
/**
使用 3 个线程 a,b,c 实现轮流交替输出字符串的每个字符,并显示行号。
控制台显示效果如下: (线程 a,b,c 也需要按照顺序输出)
1.线程 a 输出字符: ~
2.线程 b 输出字符: a
3.线程 c 输出字符: s
4.线程 a 输出字符: d
5.线程 b 输出字符: ;
6.线程 c 输出字符: 4
7.线程 a 输出字符: #
8.线程 b 输出字符: 1
9.线程 c 输出字符: e
10.线程 a 输出字符: r
*/
//打印字符串的锁
private static final Object LOCK = new Object();
//控制打印位置的指针
private static volatile int index = 0;
//打印的线程池
static ExecutorService executor = Executors.newFixedThreadPool(3);
public static void main(String[] args) {
String str = "~asd;4#1er&67qwe234#1&3sdBd1d1,@3ret#1&56ghk123#1A&34D";
String[] strs = str.split("");
executor.execute(() -> {
try {
printStringA(strs);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executor.execute(() -> {
try {
printStringB(strs);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executor.execute(() -> {
try {
printStringC(strs);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executor.shutdown();
}
public static void printStringA(String[] strs) throws InterruptedException {
while (strs.length > index) {
synchronized (LOCK) {
if (index % 3 == 0) {
//1.线程 a 输出字符:~
System.out.println( (index+1) + ".线程 a 输出字符: " +strs[index]);
index++;
// notify 随机唤醒一个持有该锁的其他线程
LOCK.notify();
} else {
// 阻塞当前线程
LOCK.wait();
}
}
}
}
public static void printStringB(String[] strs) throws InterruptedException {
while (strs.length > index) {
synchronized (LOCK) {
if (index % 3 == 1) {
System.out.println( (index+1) + ".线程 b 输出字符: " +strs[index]);
index++;
LOCK.notify();
} else {
LOCK.wait();
}
}
}
}
public static void printStringC(String[] strs) throws InterruptedException {
while (strs.length > index) {
synchronized (LOCK) {
if (index % 3 == 2) {
System.out.println( (index+1) + ".线程 c 输出字符: " +strs[index]);
index++;
LOCK.notify();
} else {
LOCK.wait();
}
}
}
}
}