Java实现使用 3 个线程 a,b,c 实现轮流交替输出字符串的每个字符,并显示行号。
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(); } } } } }
3、思路扩展
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术