最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

当我们使用synchronized关键字时,什么会被锁定?

网站源码admin106浏览0评论
本文介绍了当我们使用synchronized关键字时,什么会被锁定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在阅读线程并发问题并通过synchronized关键字处理它时,我想到的问题是,当我们使用术语lock时,它用于包含 run 方法(或线程的工作)的对象.但是为什么我们不能将术语 lock 用于定义包含 synchronized 的方法 关键字,因为这个关键字意味着一旦一个线程进入方法,那么这个线程只能在方法完成后被JVM调度器打扰?

Question comes to my mind while reading about the concurrency issues in threads and dealing with it through synchronized keyword is that,when we use the term lock it is used for the object which contains the run method (or the job of the thread).But why we cannot use the term lock for the method only whose definition contains the synchronized keyword,as this keyword means that once a thread enters the method,then this thread can only be disturbed by the JVM scheduler after the completion of the method?

我正在从头开始学习java,那里写着对象被锁定"的行,给出的原因再次以一种质疑的方式给出,即如果我们有两个同步方法会发生什么".所以我我在这里很困惑,如果只锁定方法会发生什么令人惊讶的事情?

i am studying from head first java and there is line written over there that the "object is locked" and the reason given is again in a questioning manner that is,"what happen if we have two synchronized method".So i am confuse here that what is the surprising thing that can happen if only the method is locked?

如果我问了一个模糊的问题,请原谅我,并提前致谢.

Please forgive me if i asked a vague question and thanks in advance.

推荐答案

同步时,线程获取一个object monitor.由于一次只有一个线程可以获取监视器,因此尝试获取监视器的另一个线程将被阻塞.所以从某种意义上说,没有什么是真正锁定的,除了某段代码.

When synchronizing, an object monitor is acquired by the thread. Since only one thread can acquire the monitor at a time, another thread trying to acquire it will be block. So in a sense nothing is really locked, except maybe a certain piece of code.

这篇关于当我们使用synchronized关键字时,什么会被锁定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

发布评论

评论列表(0)

  1. 暂无评论