0

Lets assume a situation like this :

enter image description here

Lets say Thread0 access the lockObject first and then Thread0 going to sleep for 1000ms.

synchronized(lockObject) {
    Thread0.sleep(1000);
}

Thread1 also waiting for access the lockObject.

What happened in these kind of situations? Is that context switching will pause for 1000ms because of the sleep(1000)?

kenWay
  • 81
  • 1
  • 6
  • What would you expect this to do if the code were to do something else for 1000ms? Why would it do something else for `sleep()`? – daniu May 15 '20 at 10:55
  • 1
    There’s rarely a context switching for just your two threads. The operating system likely will continue switching between threads, but not those two threads. – Holger May 15 '20 at 12:40
  • Re, "What happened in these kind of situations?" We re-write the application so that it doesn't `sleep()` while holding a lock! We should have designed the program from the beginning so that it never keeps any lock locked for more than maybe a millisecond. Maybe not even that. – Solomon Slow May 15 '20 at 13:15
  • P.S., Can you explain, what does "Contex switching=3ms" mean? What does "context switching will pause" mean? If thread 0 is sleeping while it owns a lock, and at the same time, thread 1 is waiting to acquire the same lock, then neither thread is _runnable_, and therefore, it would be meaningless for either thread to participate in any context switch. – Solomon Slow May 15 '20 at 16:19
  • @SolomonSlow lets say there is not any synchronized() block and wait() method. Then the two threads will access the shared object one by one because of the context switching ryt?ex - thread 1 accessing the shared object until context switching suspend it after 2ms and then thread0 will acessing the shared object for 3ms ryt? Correct me if I wrong – kenWay May 15 '20 at 16:31
  • Sounds like you are trying to learn from an old book. Most computers these days—even most cell phones—have more than one processor. Multithreading no longer just means that the OS executes this thread for so long and then switches to that thread. It's possible, even likely, for two different threads of the same process to run _simultaneously_ on two different processors. IMO, if you are not writing an operating system, then it's unproductive for you to try think about threading at the OS level. Focus instead on learning the _memory model_ of your programming language and its tools. – Solomon Slow May 15 '20 at 17:57
  • https://en.wikipedia.org/wiki/Memory_model_(programming) – Solomon Slow May 15 '20 at 17:59

1 Answers1

1

When you call Thread0.sleep(1000);, the thread does not release the lock on lockObject. So yes context switching will pause for 1000ms.

Vikas
  • 6,868
  • 4
  • 27
  • 41