前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java中线程同步Synchronized,监视器monitor和锁lock的关系是什么

java中线程同步Synchronized,监视器monitor和锁lock的关系是什么

作者头像
马克java社区
修改2021-04-23 10:48:04
7680
修改2021-04-23 10:48:04
举报
文章被收录于专栏:java大数据

线程同步Synchronized,监视器monitor和锁lock的关系 

既然有关监视器monitor的概念比较难,大家怎么解释的都有。首先我给出一下java的官方文档,也是最权威的解释:

Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor."),Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. 

源自:http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

根据官方文档,我来说说我的看法。马克-to-win: synchronized 工作机制是这样的:Java中每个对象都有一把锁与之相关联,锁控制着对象的synchronized代码。一个要执行对象的synchronized代 码的线程必须先获得那个对象的锁。(即使两个方法分别被冠以synchronized,见例子例1.9.3-b)有点儿监控(monitor)的感觉吗?

synchronized关键字使用方式有两种:synchronized方法和synchronized块。以下会给出例子:

例1.9.3

class A {

    public synchronized void f1() {

        for (int i = 0; i < 3; i++) {

            try {

                Thread.sleep(1000);

            } catch (Exception e) {

            }

            System.out.println("i = " + i);

        }

    }

}

class MyThread extends Thread {

    A a;

    public MyThread(A a) {

        this.a = a;

    }

    public void run() {

        a.f1();

    }

}

public class TestMark_to_win {

    public static void main(String[] args) {

        A a = new A();

        Thread t1 = new MyThread(a);

        Thread t2 = new MyThread(a);

        t1.start();

        t2.start();

    }

}

 

更多请见:https://blog.csdn.net/qq_44639795/article/details/103096019

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档