多线程和线程抢占同步
假设我有以下代码
public synchronized void method()
{
if(something == null)
{
something = new SomeThing();
}
//do something
}
现在假设在多线程环境中,一个线程 [Thread 1] 进入该方法,并在执行 new Something();
之后但在它能够执行之前被抢占将其分配给某物
。然后另一个线程[线程2]也尝试调用该方法。现在到底发生了什么?线程 1 获得的锁会发生什么情况?线程1的步骤会回滚吗?
Suppose I have the following piece of code
public synchronized void method()
{
if(something == null)
{
something = new SomeThing();
}
//do something
}
Now suppose in a multithreaded environment, one thread [Thread 1] enters the method and was preempted just after it executed the new Something();
but before it was able to assign it to something
. Then another thread [Thread 2] also tries to call the method. What exactly happens now? What happens to the lock that Thread 1 had acquired? Will Thread 1's steps be rolled back?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Thread1 没有放弃锁,因此它仍然拥有它。当 Thread2 准备获取锁时,它会发现它必须等待并进入 BLOCKED 状态。下次操作系统调度 Thread1 时,它将完成执行并释放锁。这使得 Thread2 可以再次被调度。
Thread1 did not give up the lock, so it still owns it. When Thread2 prepares to take the lock it will discover that it has to wait and enter a
BLOCKED
state. The next time the OS schedules Thread1 it will finish execution and release the lock. This allows Thread2 to be schedulable again.线程 2 无法进入该方法,直到线程 1 退出该方法,因为它是同步的。
最终调度程序将继续执行线程 1,线程 1 将执行 new Something() 并退出该方法。然后,线程 2 将能够进入构造了 new Something() 的函数。
锁的整体思想是线程 1 在用完锁之前不会丢失它。线程 1 在退出 method() 时解锁,然后线程 2 就能够获取它。
Thread 2 will not be able to enter the method until Thread 1 has exited it because it is synchronized.
Eventually the scheduler will get around to continuing with Thread 1, Thread 1 will execute new Something() and exit the method. Then, Thread 2 will be able to enter the function with the new Something() constructed.
The whole idea of the lock is that Thread 1 does not lose it until it is done with it. Thread 1 unlocks when it exits method(), then Thread 2 is able to acquire it.