gpt4 book ai didi

java - 等待通知传递NULL值Java

转载 作者:行者123 更新时间:2023-12-02 11:18:23 25 4
gpt4 key购买 nike

我正在尝试在具有多线程(多个线程通知和等待)的程序中实现 wait()notify()

问题

发生在两个线程wait()时,而我在notify()时,两个线程都被唤醒,这使得只有一个数据,并且两个线程都需要做,结果是一个线程获胜,失败的线程将不会收到任何NULL

这只是我的意见,您的情况可能会有所不同,因为它只发生在多线程环境中

原因

我可能会实现,notify()错误,等等,我可能不知道,而且它只会发生像20次运行,一次错误

代码

//Single Threads

/*
As seen here I am using single threads, and
if there is error, Depot Enter will shows error,
if no error means there is a data
*/

bus = (Bus) ((LinkedList<?>) Shop.ListBusRamp).poll();
System.out.println("Depot Enter: " + bus.getBusName());

/*
In here I want to pass the value into another Linked List
As earlier there is a value that I just poll.
I can offer here and pass the value, no NULL occurred yet.
*/

((LinkedList<Bus>) ListBusDepot).offer(bus);

synchronized (ListBusDepot) {
ListBusDepot.notify();
}

如此处所示,我想将值从 ListBusRamp 传递到 ListBusDepot 中,如此处所示,尚未发生 NULL,一切都很好。

//MULTI THREADS (2 THREADS TO BE EXACT)

/*
Here I want to wait for the data passed by notify
After I got the data, I want to show it.

As for why I check of Cleaners < 2?
I create so that NOT ALL can enter, only when size is 2
*/

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

//VALUE MUST NOT NULL IF REACHES HERE

bus = (Bus) ((LinkedList<?>) Shop.ListBusDepot).peek();
if (counter.getBus_Cur_Cleaners() < 2) {
counter.remBus_Cur_Depot();
counter.addBus_Cur_Mechanics();

//Here is the problem, while accessing data, it will show NULL
System.out.println("Mechanics Earlier: " + bus.getBusName() + " fixed by" + name);

bus = (Bus) ((LinkedList<?>) Shop.ListBusDepot).poll();
}
}

正如这里所看到的,发生了NULL,以及如何防止它,我想要的是如果它仍然为null(空),则在等待时不要退出循环

最佳答案

Happens when two threads wait(), while I am notify(), both of them wake

不,只有一个人会醒来。 notifyAll 将唤醒两者。

<小时/>

您正在 ListBusDepot 上同步

while (ListBusDepot.size() == 0) 

但尝试从Shop.ListBusDepot

获取
bus = (Bus) ((LinkedList<?>) Shop.ListBusDepot).peek();

这就是为什么 bus 为空。

<小时/>

考虑使用 BlockigQueue ,它将为您处理waitnotify,这样您就可以专注于您的业务逻辑。

关于java - 等待通知传递NULL值Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50103962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com