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

转载 2011年01月23日 16:34:00

在并发环境下,解决共享资源冲突问题时,可以考虑使用锁机制。
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 {
                  TimeUnit.SECONDS.sleep(3);
              catch (InterruptedException e) {
                  e.printStackTrace();
              }
           }
       }
    }
 
    public static void main(String[] args) {
       final Resource1 rs = new Resource1();
 
       new Thread() {
           public void run() {
              rs.f();
           }
       }.start();
 
       new Thread() {
           public void run() {
              rs.g();
           }
       }.start();
 
       rs.h();
    }
}
结果:
Thread-0:not synchronized in f()
Thread-0:synchronized in f()
main:not synchronized in h()
Thread-1:not synchronized in g()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
2.2 同步到多个对象锁
Resource1.java演示了三个线程(包括main线程)试图进入某个类的三个不同的方法的同步块中,这些同步块处在不同的方法中,并且是同步到三个不同的对象(synchronized (this)synchronized(syncObject1)synchronized (syncObject2)),所以对它们的方法中的临界资源访问是独立的。
Resource2.java
package com.zj.lock;
import java.util.concurrent.TimeUnit;
 
public class Resource2 {
    private Object syncObject1 = new Object();
    private Object syncObject2 = new Object();
 
    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 (syncObject1) {
           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 (syncObject2) {
           for (int i = 0; i < 5; i++) {
              System.out.println(Thread.currentThread().getName()
                     ":synchronized in h()");
              try {
                  TimeUnit.SECONDS.sleep(3);
              catch (InterruptedException e) {
                  e.printStackTrace();
              }
           }
       }
    }
 
    public static void main(String[] args) {
       final Resource2 rs = new Resource2();
 
       new Thread() {
           public void run() {
              rs.f();
           }
       }.start();
 
       new Thread() {
           public void run() {
              rs.g();
           }
       }.start();
 
       rs.h();
    }
}
结果:
Thread-0:not synchronized in f()
Thread-0:synchronized in f()
main:not synchronized in h()
main:synchronized in h()
Thread-1:not synchronized in g()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
3.Lock对象锁
除了使用synchronized外,还可以使用Lock对象来创建临界区。Resource3.java的演示效果同Resource1.javaResource4.java的演示效果同Resource2.java
Resource3.java
package com.zj.lock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public class Resource3 {
    private Lock lock = new ReentrantLock();
 
    public void f() {
       // other operations should not be locked...
       System.out.println(Thread.currentThread().getName()
              ":not synchronized in f()");
       lock.lock();
       try {
           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();
              }
           }
       finally {
           lock.unlock();
       }
    }
 
    public void g() {
       // other operations should not be locked...
       System.out.println(Thread.currentThread().getName()
              ":not synchronized in g()");
       lock.lock();
       try {
           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();
              }
           }
       finally {
           lock.unlock();
       }
    }
 
    public void h() {
       // other operations should not be locked...
       System.out.println(Thread.currentThread().getName()
              ":not synchronized in h()");
       lock.lock();
       try {
           for (int i = 0; i < 5; i++) {
              System.out.println(Thread.currentThread().getName()
                     ":synchronized in h()");
              try {
                  TimeUnit.SECONDS.sleep(3);
              catch (InterruptedException e) {
                  e.printStackTrace();
              }
           }
       finally {
           lock.unlock();
       }
    }
 
    public static void main(String[] args) {
       final Resource3 rs = new Resource3();
 
       new Thread() {
           public void run() {
              rs.f();
           }
       }.start();
 
       new Thread() {
           public void run() {
              rs.g();
           }
       }.start();
 
       rs.h();
    }
}
结果:
Thread-0:not synchronized in f()
Thread-0:synchronized in f()
main:not synchronized in h()
Thread-1:not synchronized in g()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
Thread-0:synchronized in f()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Thread-1:synchronized in g()
Resource4.java
package com.zj.lock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public class Resource4 {
    private Lock lock1 = new ReentrantLock();
    private Lock lock2 = new ReentrantLock();
    private Lock lock3 = new ReentrantLock();
 
    public void f() {
       // other operations should not be locked...
       System.out.println(Thread.currentThread().getName()
              ":not synchronized in f()");
       lock1.lock();
       try {
           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();
              }
           }
       finally {
           lock1.unlock();
       }
    }
 
    public void g() {
       // other operations should not be locked...
       System.out.println(Thread.currentThread().getName()
              ":not synchronized in g()");
       lock2.lock();
       try {
           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();
              }
           }
       finally {
           lock2.unlock();
       }
    }
 
    public void h() {
       // other operations should not be locked...
       System.out.println(Thread.currentThread().getName()
              ":not synchronized in h()");
       lock3.lock();
       try {
           for (int i = 0; i < 5; i++) {
              System.out.println(Thread.currentThread().getName()
                     ":synchronized in h()");
              try {
                  TimeUnit.SECONDS.sleep(3);
              catch (InterruptedException e) {
                  e.printStackTrace();
              }
           }
       finally {
           lock3.unlock();
       }
    }
 
    public static void main(String[] args) {
       final Resource4 rs = new Resource4();
 
       new Thread() {
           public void run() {
              rs.f();
           }
       }.start();
 
       new Thread() {
           public void run() {
              rs.g();
           }
       }.start();
 
       rs.h();
    }
}
结果:
Thread-0:not synchronized in f()
Thread-0:synchronized in f()
main:not synchronized in h()
main:synchronized in h()
Thread-1:not synchronized in g()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()
Thread-0:synchronized in f()
main:synchronized in h()
Thread-1:synchronized in g()

本文出自 “子 孑” 博客,请务必保留此出处http://zhangjunhd.blog.51cto.com/113473/70300

相关文章推荐

Java锁 到底锁的是哪个对象?

一段synchronized的代码被一个线程执行之前,他要先拿到执行这段代码的权限,在java里边就是拿到某个同步对象的锁(一个对象只有一把锁); 如果这个时候同步对象的锁被其他线程拿走了,他(这个线...
  • fyxxq
  • fyxxq
  • 2013-01-12 20:02
  • 9673

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

Java:使用synchronized和Lock对象获取对象锁 标签:synchronized Java 对象锁 Lock 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出...

Ubuntu14.04 Matlab 2014b启动器(使用matlab自带图标)

[Desktop Entry] Categories=Development;Matlab; Comment[zh_CN]=Matlab:The Language of Technical Compu...

InSAR学习(六)形变监测结果的可视化方法

DINSAR

InSAR学习(三)DInSAR基本原理

DInSAR基本原理的推导

InSAR学习(四)高级的InSAR技术之基本原理

PS SBAS

博朗的设计理念

博朗的设计理念源于1955年,经过几十年的发展完善,这一特点鲜明、注重功能的设计风格被设计大师迪特·拉姆斯(Dieter Rams)概括总结为产品设计的十原则

虚拟机 ubantu DORIS 的那些事(上)

虚拟机 ubantu DORIS 的那些事 谨以此文献给一无所知,也没有半途放弃的自己。 下面是今天学习的笔记。最终目的是学习InSAR处理软件Doris,因为需要在Ubantu系统下安装,这里首先安...

InSAR-DInSAR 技术细节(四) Range spectral shift

Range spectral shift这个问题在斜坡效应中其实已经说过了。理解这个问题的关键在于: 知道频率是相位的微分(但这个(干涉数据的)频率跟载频、采样频率等其他的频率并不能混为一谈)。这样...

InSAR-DInSAR 技术细节(六)相干与相干斑

随机相位导致相干斑 一副影像的相位是随机的,原因: One pixel of a radar image usually represents a surface of several tens ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)