等待通知传递NULL值Java

时间:2018-04-30 15:48:17

标签: java multithreading synchronization

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

问题

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

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

原因

我可能会实施,通知()错误等等,我可能不知道,而且只会发生 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,如何防止它,我想要的只是如果它仍为空(空),请不要在等待时退出循环

1 个答案:

答案 0 :(得分:1)

  

当两个线程等待()时发生,而我是notify(),两者都是   唤醒

不,只有一个会醒来。 notifyAll会唤醒他们。

您正在ListBusDepot

进行同步
while (ListBusDepot.size() == 0) 

但请尝试从Shop.ListBusDepot

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

这就是bus为空的原因。

考虑使用BlockigQueue,它会为您处理waitnotify,因此您可以专注于您的商家登录。

相关问题