简体   繁体   中英

synchronized block inside infinite loop

I have two threads, say T1 and T2 , which act concurrently on the same object obj :

class T1 extends Thread {
  public void run() {
    while(true) {
      synchronized(obj) {
        while(condition) {
          ...do something...
          obj.wait();
        }
        ...do something else...
        obj.notify();
      }
    }
  }
}


class T2 extends Thread {
  public void run() {
    while(true) {
      synchronized(obj) {
        while(!condition) {
          ...do something...
          obj.wait();
        }
        ...do something else...
        obj.notify();
      }
    }
  }
}

So, say T1 acquires lock first, enters the while(condition) loop and suspends himself. On the other hand, T2 is now free to acquire lock: !condition is not met so it doesn't enter inner while loop, it does something else and then calls obj.notify() .
What I'm expecting is: T1 wakes up, acquires lock and so on, but most of the times what I see is that T1 is not able to acquire lock and therefore T2 executes again.

I'm asking you if this behavior is caused by the while(true) loop, or what else.

In threading there are no guarantees. One or the other of the threads will hit the synchronized block first and you should never count on either behaviour.

In practice the currently running thread has no "startup" cost so is more likely to hit the synchronized block first.

The key here is to not worry about which thread is doing what when but to focus on reducing contention. Get as much processing as possible out of that synchronized block and evaluate whether you really need to synchronize everything or whether you can synchronize just a small part of the work, or have multiple different objects to lock against.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM