-1

There are 10 threads wants to call a method method1() from a class. All the 10 hits the methods at the same time . If the method is synchronized then only thread will get the lock and other 9 threads will be placed in waiting state. In case , the first thread completes the execution then it calls notify(). In this scenario, which of the 9 thread get the CPU cycle . Which are the parameter involved in this selection?

Thanks.

JavaUser
  • 25,542
  • 46
  • 113
  • 139
  • 1
    The short answer is _any_ ... A [Java thread](https://stackoverflow.com/a/38236471/1152524) that's sync'd is a kernel thread that is blocked by a mutex or semaphore, in which case, it's up to the kernel, and Windows/Linux/macOS handles threading much differently than `[insert system here]`. Without code to determine any sort of possible sequencing, it cannot be determined which thread would actually "go next"; and even with code, if it's simply a [`synchronized`](https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html) method, the answer remains the same. – txtechhelp Feb 12 '19 at 07:20
  • Regardless of which thread goes first, identification of the working thread is possible. It is possible to provide names for threads when creating them using `new Thread(String name)`. Then, inside the method of interest, a call to `Thread.currentThread().getName()` will reveal the threads name. Most other threads like Swings Event Dispatch Thread or the fork-join-pool threads have names. If it is about to identifiy which thread does the work, `Thread.currentThread()` will help. –  Feb 12 '19 at 07:22
  • 1
    A different, short answer is; The Java Language Specification (JLS) does not say anything about the order in which the waiting threads "wake up." `synchronized` blocks in Java are not intended for any other purpose except to prevent two or more threads from accessing the same data at the same time. By not saying which thread wakes up next when there is contention for a lock object, the JLS gives Java implementors freedom to choose the most efficient locking algorithm for any given hardware platform and operating system. – Solomon Slow Feb 12 '19 at 14:30

1 Answers1

0

Any thread that is Runnable i.e. either Running or Ready will get notified. There is no way to figure out exactly which thread.

vavasthi
  • 922
  • 5
  • 14