Java Thread Synchronized object for wait and notify

When we are using wait and notify in thread environment. I have a class to process data as background process. And when there is no data to process it should call wait.

synchronized(some_object){
   wait();
}

In another class I am adding the data again. I need call notify() method.

synchronized(some_object){
   runnabale_object.notify();
}

Why i should use same object for synchronized block in those two different class. As i read synchronize is used to

The "Synchronized" keywords prevents concurrent access to a block of code or object by multiple Threads.

But these two are different block. But i can understand the problem when we use multiple threads. While one thread block other can call notify before the same thread call notify.

My Questions

  • Can we use different lock objects (synchronized(object)) for single threaded environment?
  • Best way of use same lock object when we have wait and notify in different classes?

  • Can we use different lock objects (synchronized(object)) for single threaded environment?

    In a single threaded environment, you don't need the locks. You can use anything you want or nothing at all.

    In a single threaded environment you can guarantee no thread is wait()ing so the notify() will not do anything.

    Best way of use same lock object when we have wait and notify in different classes?

    When you notify(), you must perform a state change. When you wait() in a loop you much check for that state change. If you don't do this you can have two problem.

  • the notify() is lost
  • the wait() wakes spuriously, ie no notify.

  • when there is no data to process it should call wait.

    Not when, but while.

    Wait and notify are low-level primitive operations that are meant to be used in a very specific way.

    In a consumer thread:

    synchronized(lock) {
        while (thereIsNothingToProcess()) {
            lock.wait();
        }
        processSomething();
    }
    

    In a producer thread:

    synchronized(lock) {
        makeSomethingAvailableToProcess();
        lock.notifyAll();    //or lock.notify() if you think you can get away with it.
    }
    

    If you follow this exact pattern, then:

  • You will not run into trouble when multiple consumers are competing for the same thing-to-be-processed,
  • You will not run into trouble because of spurious wakeups, and
  • You will not run into trouble because of the lost notification problem.
  • 链接地址: http://www.djcxy.com/p/76254.html

    上一篇: 在Java中的“this”或私人对象上同步?

    下一篇: 用于等待和通知的Java线程同步对象