查看: 691|回复: 3

[Java新手区] How Java shares resources

[复制链接]
  • TA的每日心情
    开心
    2015-11-19 17:27
  • 签到天数: 1 天

    [LV.1]初来乍到

    发表于 2017-9-18 22:57:03 | 显示全部楼层 |阅读模式
      Java has built-in support to prevent collisions over one kind of resource: the memory in an object. Since you typically make the data elements of a class private and access that memory only through methods, you can prevent collisions by making a particular method synchronized. Only one thread at a time can call a synchronized method for a particular object (although that thread can call more than one of the object’s synchronized methods). Here are simple synchronized methods:
    [size=+1]synchronized void f() { /* ... */ }synchronized void g(){ /* ... */ }
    [size=+0]Each object contains a single lock (also called a monitor) that is automatically part of the object (you don’t have to write any special code). When you call any synchronized method, that object is locked and no other synchronized method of that object can be called until the first one finishes and releases the lock. In the example above, if f( ) is called for an object, g( ) cannot be called for the same object until f( ) is completed and releases the lock. Thus, there’s a single lock that’s shared by all the synchronized methods of a particular object, and this lock prevents common memory from being written by more than one method at a time (i.e. more than one thread at a time).

    [size=+0]There’s also a single lock per class (as part of the Class object for the class), so that synchronized static methods can lock each other out from static data on a class-wide basis.

    [size=+0]Note that if you want to guard some other resource from simultaneous access by multiple threads, you can do so by forcing access to that resource through synchronized methods.


    您需要登录后才可以回帖 登录 | 注册青鸟豆号

    本版积分规则

    Copyright 1999-2017 Beijing Aptech Beida Jade Bird Information Technology Co.,Ltd

    北大青鸟IT教育 北京阿博泰克北大青鸟信息技术有限公司 版权所有

    京ICP备11045574号-3 京公网安备11010802013845号

    快速回复 返回顶部 返回列表