我的MultiThread有问题,因为它无法独立工作,但是,有2个不同的线程。等待并通知
我的主要课程:
Mechanics mechanics = new Mechanics(busShop, "Mechanic 1");
Mechanics mechanics2 = new Mechanics(busShop, "Mechanic 2");
Thread thMechanic = new Thread(mechanics);
Thread thMehanic2 = new Thread(mechanics2);
thMechanic.start();
thMehanic2.start();
创建两个不同的独立线程,现在我这样做:
我的力学课程:
@Override
public void run() {
fixEngine();
}
private void fixEngine() {
while (true) {
busShop.FixEngine(MechanicsName);
}
}
运行时,只需执行此功能:
public void FixEngine(String mechanicsName) {
//Call mechanics to fix engine
Bus bus;
synchronized (EntryRamp.ListBusDepotWaiting) {
while (EntryRamp.ListBusDepotWaiting.size() == 0) {
try {
EntryRamp.ListBusDepotWaiting.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (ListBusEngineFix) {
//Fix the mechanics
bus = (Bus) ((LinkedList<?>) EntryRamp.ListBusDepotWaiting).poll();
((LinkedList<Bus>) ListBusEngineFix).offer(bus);
System.out.println("Bus: " + bus.getBusName() + "is being fixed by" + mechanicsName);
ListBusEngineFix.notify();
//Done fix
}
}
通知来自何处。
synchronized (ListBusDepotWaiting) {
//If depot is not 2
if (ListBusDepotWaiting.size() < 2 && ListBusRamp.size() == 0) {
//If empty we can start moving
bus = (Bus) ((LinkedList<?>) ListBusWaiting).poll();
((LinkedList<Bus>) ListBusRamp).offer(bus);
System.out.println("RAMP: " + bus.getBusName() + "Enter the RAMP");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bus = (Bus) ((LinkedList<?>) ListBusRamp).poll();
((LinkedList<Bus>) ListBusDepotWaiting).offer(bus);
System.out.println("DEPOT: " + bus.getBusName() + "Enter the DEPOT");
ListBusDepotWaiting.notify();
}
}
运行时显示:
RAMP: Bus 1Enter the RAMP
DEPOT: Bus 1Enter the DEPOT
RAMP: Bus 2Enter the RAMP
DEPOT: Bus 2Enter the DEPOT
Bus: Bus 1is being fixed byMechanic 1
RAMP: Bus 3Enter the RAMP
Bus: Bus 1being cleaned
Bus: Bus 2is being fixed byMechanic 2
总线1不会立即处理,但它等待总线2到来,并与另一个线程一起工作。这意味着线程1无法自行完成,您可能在这里看不到,但是机制1和机制2同时完成,而机制1首先完成任务。任何想法的人?