Java threads and synchronized blocks

前端 未结 3 592
心在旅途
心在旅途 2021-02-14 18:09

Suppose I\'m executing a synchronized block of code inside some thread and within the synchronized block I call a method that spawns another thread to

相关标签:
3条回答
  • 2021-02-14 18:23

    If someMethod() is invoked first, its the classical example of a deadlock.

    Is what I have written even legal?
    ---- Yes it is perfectly legal syntactically.

    So when I execute someOtherMethod() in order to create an instance of Runnable in what kind of scope does the code before the return statement run? ----If the someOtherMethod() is invoked from within someMethod() then its in scope of the synchronized block of the someMethod() method.

    0 讨论(0)
  • 2021-02-14 18:32

    There's nothing wrong about this code. Before the return statement in someOtherMethod(), the code is running in the synchronized block of someMethod(). After the new thread starts, it will block on the synchronized statement inside the run() method until it obtains a lock on lock_obj (at the earliest, whenever someMethod() exits its synchronized block).

    0 讨论(0)
  • 2021-02-14 18:44

    You are still holding the lock during the creation of runnable and the thread, but after you call start and before the thread actually picks up you are relinquishing the lock. The new thread will have to compete for the lock with other threads.

    0 讨论(0)
提交回复
热议问题