使用Semaphore实现双线程交替打印异常,求修复方案
问题修复:Semaphore实现FooBar交替打印
问题根源
你代码的核心问题是没有真正创建两个独立线程,而是在主线程中串行调用了foo()和bar()方法。这导致信号量的交替控制逻辑完全无法生效——主线程会先执行完foo的5次循环(输出5个Foo),再执行bar的5次循环(输出5个Bar),自然得不到交替输出的结果。
修复后的代码
public class PrintThread { // 修正类名符合Java规范 private int n = 5; private Semaphore f = new Semaphore(1); private Semaphore t = new Semaphore(0); public void foo(Runnable printFoo) throws InterruptedException { for (int i = 0; i < n; i++) { f.acquire(); printFoo.run(); t.release(); } } public void bar(Runnable printBar) throws InterruptedException { for (int i = 0; i < n; i++) { t.acquire(); printBar.run(); f.release(); } } public static void main(String[] args) { PrintThread pt = new PrintThread(); Runnable printFo = () -> System.out.print("Foo"); Runnable printBa = () -> System.out.print("Bar"); // 创建两个独立线程,分别执行foo和bar逻辑 Thread fooThread = new Thread(() -> { try { pt.foo(printFo); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); Thread barThread = new Thread(() -> { try { pt.bar(printBa); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); // 启动两个线程,让它们并发执行 fooThread.start(); barThread.start(); } }
关键修改说明
- 创建独立线程:用
Thread类分别封装foo和bar的执行逻辑,确保两个方法在不同线程中并发运行,让信号量的交替控制逻辑生效 - 线程中断处理:捕获
InterruptedException后调用Thread.currentThread().interrupt(),保留线程中断状态,符合Java并发编程规范 - 修正类名:将
printThread改为PrintThread,遵守Java大驼峰类命名规范
执行结果
运行修复后的代码,会输出预期的交替字符串:
FooBarFooBarFooBarFooBarFooBar
内容的提问来源于stack exchange,提问作者Karthikeyan
相关产品推荐
相关产品推荐

