Java:使用 synchronized和Lock对象获取对象锁

在并发环境下,解决共享资源冲突问题时,可以考虑使用锁机制。
1. 对象的锁
所有对象都自动含有单一的锁。
JVM 负责跟踪对象被加锁的次数。如果一个对象被解锁,其计数变为 0 。在任务(线程)第一次给对象加锁的时候, 计数变为 1 。每当 这个相同的任务(线程)在此对象上获得锁时,计数会递增。
只有首先获得锁的任务(线程)才能继续获取该对象上的多个锁。
每当任务离开一个 synchronized 方法,计数递减,当计数为 0 的时候,锁被完全释放,此时别的任务就可以使用此资源。
2.synchronized 同步块
2.1 同步到单一对象锁
当使用同步块时,如果方法下的同步块都同步到一个对象上的锁,则所有的任务(线程)只能互斥的进入这 些同步块。
Resource1.java 演示了三个线程(包括 main 线程)试图进入某个类的三个不同的方法的同步块中,虽然这些同步块处在不同的方法中,但由于是同步 到同一个对象(当前对象 synchronized ( this ) ),所以对它们的方法依然是互斥的。
Resource1.java
package com.zj.lock;
import java.util.concurrent.TimeUnit;
 
public class Resource1 {
    public void f() {
       // other operations should not be locked...
       System. out .println(Thread.currentThread ().getName()
              + ":not synchronized in f()" );
       synchronized ( this ) {
           for ( int i = 0; i < 5; i++) {
              System. out .println(Thread.currentThread ().getName()
                     + ":synchronized in f()" );
              try {
                  TimeUnit. SECONDS .sleep(3);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
           }
       }
    }
 
    public void g() {
       // other operations should not be locked...
       System. out .println(Thread.currentThread ().getName()
              + ":not synchronized in g()" );
       synchronized ( this ) {
           for ( int i = 0; i < 5; i++) {
              System. out .println(Thread.currentThread ().getName()
                     + ":synchronized in g()" );
              try {
                  TimeUnit. SECONDS .sleep(3);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
           }
       }
    }
 
    public void h() {
       // other operations should not be locked...
       System. out .println(Thread.currentThread ().getName()
              + ":not synchronized in h()" );
       synchronized ( this ) {
           for ( int i = 0; i < 5; i++) {
              System. out .println(Thread.currentThread ().getName()
                     + ":synchronized in h()" );
              try {
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值