多线程Java,但只有一个线程工作

时间:2018-04-18 07:16:41

标签: java multithreading concurrency synchronized

我的Java线程不能独立工作,如何解决?这是最初的主要内容:

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();

到目前为止没问题,按预期工作,所以机械师这样做:

public void run() {
    fixEngine();
}

private void fixEngine() {
    while (true) {
        busShop.FixEngine(MechanicsName);
    }
}

正如此处所见,它可以永久修复引擎,在修复引擎功能中:

public static List<Bus> ListBusEngineFix = new LinkedList();

 public void FixEngine(String mechanicsName) {
        Bus bus;

        synchronized (ListBusEngineFix) {
            System.out.println("Working Thread: " + Thread.currentThread().getName());
            while (ListBusEngineFix.size() == 0) {
                try {
                    ListBusEngineFix.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        //Wait for notify if empty

        try {
            Thread.sleep(10000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //IF EACH THREAD RUNS INDEPENDENTLY IT WILL BT ONLY LESS THAN 20 SECONDS
        //BUT THIS CASE, MY PROGRAM WAIT FOR PREVIOUS THREAD, WHICH CAUSE MORE THAN 20 SECONDS.
}

结果:

Working Thread: Thread-6
Working Thread: Thread-7

两个线程都按预期运行

前10秒:

Bus: Bus 1by Mechanic 1

另外10秒:

Bus: Bus 2by Mechanic 1

我的怀疑是机械师1(线程)锁定本身,因此机械师2(线程)无法帮助它,因为机械师1完成所有任务。无论如何,如何解决它?

注意:我只在早期使用synchronized进行等待(通知),如果我没有说它会有网络监控异常。

编辑:添加了LinkedList和Notify以便澄清,提供的所有列表都是链接列表。一个班级。

编辑2: 好的我已经修好了这个:

synchronized (ListBusDepotWaiting) {
    while (ListBusDepotWaiting.size() == 0) {
        try {
            ListBusDepotWaiting.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

//Engine not yet fixed
//Notify the Mechanics to fix car
if (ListBusEngineFix.size() < 2) {
    //Means that mechanics is empty
    bus = (Bus) ((LinkedList<?>) ListBusDepotWaiting).poll();
    ((LinkedList<Bus>) ListBusEngineFix).offer(bus);
    if (ListBusEngineFix.size() == 1) {
        synchronized (ListBusEngineFix) {
            ListBusEngineFix.notify();
        }
    }

}

现在他们可以立即致电并通知,但原始问题仍然存在,无法为Mechanic2提供工作

1 个答案:

答案 0 :(得分:1)

waitnotify应在同一个monotor对象上执行。

在您的代码中,您正在等待

ListBusEngineFix.wait();

notify

BusShop.ListBusDepotWaiting.notify();

所以等待的线程将被阻止。