在并发环境下,解决共享资源冲突问题时,可以考虑使用锁机制。
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.java;Resource4.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()
相关推荐
3. 锁住整个对象:当`synchronized`后面跟的是`this`或者类实例时,锁住的是整个对象,不允许其他线程同时访问对象的所有`synchronized`方法和代码块。 二、Lock接口 Lock接口提供了更灵活的锁控制,比`...
标题中的"java 多线程synchronized互斥锁demo"指的是一个示例,展示了如何在多线程环境下使用`synchronized`关键字创建互斥锁,确保同一时间只有一个线程可以访问特定的代码块或方法。 描述中的"一个多线程访问的同...
对象锁是针对类的实例对象而言的,当一个线程访问某个对象的非静态 synchronized 方法或同步代码块时,会获取到该对象的锁。这种锁确保了同一时间只有一个线程能访问该对象的成员变量。例如: ```java public class...
当线程试图进入同步区域时,会尝试获取对象的锁,如果成功,则执行同步代码,否则等待。离开同步区域时,会释放锁。 ### 3. 是否可重入? 如上所述,`synchronized`是可重入的,这意味着一个线程可以多次进入持有...
* Lock对象是Java中的一个锁机制,提供了比synchronized方法和语句更好的性能和灵活性。 * Lock对象可以用来解决线程同步问题,提供了比synchronized方法和语句更好的性能和灵活性。 * 在使用Lock对象时,需要注意锁...
在多线程编程中,确保线程安全是至关重要的,特别是在Java中,有两种主要的同步机制:`synchronized`和`Lock`。本文将详细解释这两种机制以及它们的基础概念。 首先,我们需要理解什么是同步和临界资源。同步是指在...
2. **无法超时**:使用`synchronized`时,线程可能无限期等待锁的释放。`Lock`的`tryLock(long time, TimeUnit unit)`方法允许设置等待时间,超时未获得锁则返回。 3. **读写分离**:`synchronized`无法区分读操作...
Java synchronized关键字和Lock接口实现原理 Java 中的 synchronized 关键字和 Lock 接口是两种常用的线程同步机制,它们都可以用来解决并发问题。下面我们将详细介绍 synchronized 关键字和 Lock 接口的实现原理。...
ReentrantLock支持公平锁和非公平锁的选择,公平锁保证按照等待时间顺序获取锁,而非公平锁则可能让等待时间短的线程优先获得锁。Lock还提供了一些synchronized不具备的功能,比如: 1. 可以尝试获取锁,即tryLock...
C++标准库提供了多种工具来支持并发编程,其中包括`synchronized`关键字,尽管它在C++中并不直接存在,但在Java中广泛使用。在C++中,我们通常使用`mutex`(互斥量)来达到类似的效果。 对象锁,也称为互斥锁,是一...
- **synchronized**支持可重入性,即同一个线程可以多次获取同一个对象的锁,而不会导致死锁。 - **Lock**接口也提供了可重入锁的实现。 2. **灵活性**: - **Lock**接口提供了更多的灵活性,例如: - 可以尝试...
对于静态(`static`)方法,`synchronized`关键字锁定的是类的Class对象,因此,无论有多少个类的实例,所有线程在访问静态同步方法时都需要获取类的Class对象锁。这意味着,即使有多个类实例,所有线程也无法同时执行...
3. **异常处理**:使用`Lock`时,必须在`finally`块中释放锁,否则可能导致锁泄漏;而`synchronized`则在异常情况下自动解锁。 总结来说,`synchronized`简洁易用,适用于大部分简单同步需求,而`Lock`提供了更强大...
- **代码块同步**:使用`synchronized`关键字包围代码块,可以指定锁对象。例如:`synchronized (lockObject) { // code }`。 2. **重要特性**: - **原子性**:保证了同步区域内的操作要么全部完成,要么一个都...
在Java多线程编程中,`Lock`接口是Java并发包(`java.util.concurrent.locks`)提供的一种高级锁机制,相比传统的`synchronized`关键字,它提供了更灵活的控制方式。Lock接口的主要实现类是`ReentrantLock`,在Java 5...
Java对象锁和类锁是Java多线程编程中至关重要的概念,它们是通过`synchronized`关键字来实现的,用于确保代码在并发环境下的线程安全。在这个全面解析中,我们将深入探讨这两个锁机制,理解它们的工作原理以及如何在...
在Java并发编程中,理解和熟练...总的来说,Java并发编程中的锁机制是确保线程安全的关键,理解并熟练使用`synchronized`和`ReentrantLock`,以及相应的等待/通知机制,能够帮助开发者设计出高效且可靠的多线程程序。
4. **Lock 和 Unlock**: `lock` 方法使用 `while` 循环尝试获取锁,若获取失败则继续尝试;`unlock` 方法简单地将 `state` 设为 0 来释放锁。 #### 四、自定义锁测试 为了验证自定义锁的效果,我们可以创建多个...
通过 synchronized 关键字,我们可以对对象锁和类锁进行操作,从而实现线程安全。 synchronized 关键字的原理 synchronized 关键字的原理是通过加锁和释放锁来实现线程安全的。加锁是指在访问共享资源时,先锁定...