Java线程启动后未运行 桥梁车辆死锁模拟程序无输出问题排查
文件拆分问题解答
你当前的代码不需要拆分文件,全量代码只包含一个public类Cars,只要将文件命名为Cars.java即可正常编译运行,单文件完全满足需求,无需做拆分操作。
无输出问题原因及修复方案
没有输出的核心原因是你继承Thread类后,没有重写类的run()方法:
Thread类调用start()启动后,默认只会执行内部的run()方法,你将所有业务逻辑都放在了自定义的go()方法中,线程启动后go()从未被调用,因此没有任何内容输出。- 另外代码里还有一处隐性bug:西向车辆的打印逻辑里,你误把字符串拼接的
+写成了赋值符=,会导致name变量被意外覆盖:System.out.println(name = " are attempting to cross.");
具体修复步骤
- 给
ExtendThread类添加重写的run()方法,在内部调用你已经写好的go()方法,或者直接将go()方法改名为run()并添加@Override注解即可 - 修正西向车辆打印逻辑的赋值bug,将
=改为+
修正后的完整代码如下:
import java.util.concurrent.*; public class Cars { // 静态内部类实现线程逻辑 static class ExtendThread extends Thread { Semaphore sem; String name; public ExtendThread(Semaphore sem, String name) { super(name); this.sem = sem; this.name = name; } // 重写Thread的run方法 @Override public void run() { go(); } // 业务模拟逻辑 public void go() { // 西向车辆逻辑 if (this.getName().equals("Westbound Cars")) { try { System.out.println(name + " are waiting to cross."); sem.acquire(); // 修正了原来的赋值bug System.out.println(name + " are attempting to cross."); for (int i = 1; i < 9; i++) { System.out.println("Westbound car " + i + " is waiting to cross."); Thread.sleep(1000); System.out.println("Westbound car " + i + " has crossed."); Thread.sleep(1000); } } catch (InterruptedException exc) { System.out.println(exc); } System.out.println(name + " have crossed the bridge."); sem.release(); } // 东向车辆逻辑 else { System.out.println(name + " are waiting to cross the bridge."); try { System.out.println(name + " is waiting to cross."); sem.acquire(); System.out.println(name + " is attempting to cross."); for (int i = 1; i < 9; i++) { System.out.println("Eastbound car " + i + " is waiting to cross."); Thread.sleep(1000); System.out.println("Eastbound car " + i + " has crossed."); Thread.sleep(1000); } } catch (InterruptedException exc) { System.out.println(exc); } System.out.println(name + " have crossed the bridge."); sem.release(); } } } public static void main(String [] args) throws InterruptedException { Semaphore sem = new Semaphore(1); ExtendThread exTh1 = new ExtendThread(sem,"Westbound Cars"); ExtendThread exTh2 = new ExtendThread(sem,"Eastbound Cars"); exTh1.start(); exTh2.start(); exTh1.join(); exTh2.join(); } }
内容的提问来源于stack exchange,提问作者Samantha Baughman
相关产品推荐
相关产品推荐

