
本文深入探讨java并发编程中的同步机制,重点解析`synchronized`关键字在方法和代码块中的应用,以及`wait()`、`notify()`和`notifyall()`方法实现线程间通信的原理。文章通过具体场景分析了共享资源访问的线程安全性问题,强调了正确使用锁对象的重要性,并提供了示例代码,帮助读者理解如何避免数据不一致和实现有效的线程协作。
在多线程环境中,为了保证共享数据的完整性和一致性,Java提供了多种同步机制。其中,synchronized关键字是最基本也是最常用的方式,它基于监视器(Monitor)锁实现。每个Java对象都可以作为一个监视器锁,当一个线程进入synchronized代码块或方法时,它会尝试获取该对象的锁。如果锁已被其他线程持有,当前线程就会被阻塞,直到锁被释放。
synchronized关键字可以用于修饰方法或代码块。当修饰方法时,它锁定的是当前实例对象(对于静态方法,锁定的是类的Class对象);当修饰代码块时,它锁定的是括号中指定的对象。
考虑以下场景,一个共享列表a和两个操作它的方法:
import java.util.ArrayList;
import java.util.List;
public class SynchronizedExample {
private List<Integer> a = new ArrayList<>();
// 方法foo使用synchronized块来保护对列表a的写入操作
public void foo(int i) {
synchronized (a) { // 锁定列表a对象
a.add(i);
System.out.println(Thread.currentThread().getName() + " added: " + i + ", current size: " + a.size());
}
}
// 方法goo读取列表a的大小
public int goo() {
// 错误的示例:未同步访问共享资源
// return a.size();
// 正确的同步方式:也需要锁定列表a对象
synchronized (a) {
int size = a.size();
System.out.println(Thread.currentThread().getName() + " read size: " + size);
return size;
}
}
public static void main(String[] args) throws InterruptedException {
SynchronizedExample example = new SynchronizedExample();
// 线程1执行foo
Thread t1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
example.foo(i);
try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}, "WriterThread");
// 线程2执行goo
Thread t2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
example.goo();
try { Thread.sleep(15); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
}, "ReaderThread");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final size of list a: " + example.a.size());
}
}分析:
立即学习“Java免费学习笔记(深入)”;
结论: 只要访问的是同一个共享对象,并且使用了相同的锁对象进行同步,那么在任何时刻,只有一个线程能够执行受该锁保护的代码块。如果对共享资源的访问没有全部同步,则无法保证线程安全。
wait(), notify(), notifyAll()是Object类的方法,用于实现线程间的协作和通信。它们必须在synchronized代码块或方法内部调用,并且操作的锁对象必须是当前线程所持有的监视器锁。
考虑一个使用wait()和notifyAll()的同步方法:
public class WaitNotifyExample {
private boolean conditionMet = false;
public synchronized void fooWithWaitNotify() {
System.out.println(Thread.currentThread().getName() + " entered fooWithWaitNotify.");
// do stuff before waiting
System.out.println(Thread.currentThread().getName() + " doing stuff before wait.");
// 假设某个条件满足后才需要通知
if (!conditionMet) {
try {
System.out.println(Thread.currentThread().getName() + " is about to wait, releasing lock.");
wait(); // 释放当前对象的锁,并进入等待状态
System.out.println(Thread.currentThread().getName() + " woke up and re-acquired lock.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// do stuff after waiting or if conditionMet was true initially
System.out.println(Thread.currentThread().getName() + " doing stuff after wait/condition met.");
// 模拟条件满足,通知其他等待线程
if (Thread.currentThread().getName().equals("NotifierThread")) {
conditionMet = true; // 改变条件
System.out.println(Thread.currentThread().getName() + " notifying all waiting threads.");
notifyAll(); // 通知所有等待在当前对象上的线程
}
System.out.println(Thread.currentThread().getName() + " exiting fooWithWaitNotify.");
}
public static void main(String[] args) throws InterruptedException {
WaitNotifyExample example = new WaitNotifyExample();
Thread t1 = new Thread(() -> {
example.fooWithWaitNotify();
}, "WaiterThread");
Thread t2 = new Thread(() -> {
try {
Thread.sleep(100); // 确保WaiterThread先进入等待
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
example.fooWithWaitNotify(); // 这个线程会触发notifyAll
}, "NotifierThread");
t1.start();
t2.start();
t1.join();
t2.join();
}
}分析:
立即学习“Java免费学习笔记(深入)”;
关键点: wait()会释放锁,而notify()/notifyAll()不会释放锁,它们只是将等待线程从等待队列移到同步队列,等待获取锁。
wait()和notify()/notifyAll()是基于对象监视器的机制,而不是直接操作Thread实例。这意味着你不能直接“通知”一个特定的Thread对象。相反,你需要让需要被通知的线程在一个共享的锁对象上调用wait(),而通知者则在该同一个共享锁对象上调用notify()或notifyAll()。
如果你的目标是通知一个由Lambda表达式创建的线程,你需要确保这个Lambda表达式所运行的线程能够访问到一个共享的锁对象,并且这个锁对象也能够被通知者访问。
public class A implements Runnable {
Thread b;
// 声明一个共享的锁对象,可以是this,也可以是专门创建的Object
private final Object lock = new Object();
private boolean bStarted = false;
public void foo() {
b = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " (lambda thread) started.");
synchronized (lock) { // Lambda线程在lock对象上等待
bStarted = true;
lock.notify(); // 通知foo方法b线程已经启动
try {
System.out.println(Thread.currentThread().getName() + " (lambda thread) waiting for notification...");
lock.wait(); // 等待goo方法的通知
System.out.println(Thread.currentThread().getName() + " (lambda thread) received notification from goo!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(Thread.currentThread().getName() + " (lambda thread) finished.");
}, "LambdaThread-B");
synchronized (lock) {
b.start();
// 等待LambdaThread-B启动并通知
while (!bStarted) {
try {
lock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Main thread: LambdaThread-B has started.");
}
}
public void goo() {
synchronized (lock) { // goo方法也在同一个lock对象上同步
System.out.println(Thread.currentThread().getName() + " in goo, notifying LambdaThread-B.");
lock.notify(); // 通知等待在lock对象上的线程
}
}
@Override
public void run() {
// This run method is not directly used in the example but is required by Runnable
}
public static void main(String[] args) throws InterruptedException {
A instance = new A();
instance.foo(); // 启动lambda线程
Thread.sleep(1000); // 确保lambda线程有时间进入等待状态
instance.goo(); // 通知lambda线程
instance.b.join(); // 等待lambda线程结束
System.out.println("All threads finished.");
}
}分析:
立即学习“Java免费学习笔记(深入)”;
通过这种方式,即使你没有直接的Thread引用来操作,只要能够访问到同一个共享的锁对象,就可以实现线程间的通信。
Java的同步机制是构建健壮并发应用程序的基础。正确理解和应用synchronized、wait()、notify()和notifyAll()至关重要。
通过深入理解这些机制并遵循最佳实践,开发者可以有效地构建安全、高效的并发Java应用程序。
以上就是Java并发编程中的同步机制深度解析的详细内容,更多请关注php中文网其它相关文章!
编程怎么学习?编程怎么入门?编程在哪学?编程怎么学才快?不用担心,这里为大家提供了编程速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号