多线程同步:synchronized关键字、Lock接口与CountDownLatch等同步工具
在多线程编程中,同步是一个至关重要的概念,它用于确保多个线程在访问共享资源时的正确性和一致性。以下详细介绍synchronized关键字、Lock接口以及CountDownLatch等同步工具。
synchronized关键字
synchronized是Java内置的同步机制。它可以用于修饰方法或代码块。
修饰实例方法
当一个实例方法被synchronized修饰时,同一时刻只有一个线程能够进入该方法,因为锁对象是当前实例。例如:
public class SynchronizedExample {
private int count = 0;
public synchronized void increment() {
count++;
}
}
修饰静态方法
对于静态方法,锁对象是类的Class对象,这保证了在多线程环境下对静态资源的安全访问。
修饰代码块
通过指定锁对象,可以更细粒度地控制同步范围。比如:
public class SynchronizedBlockExample {
private Object lock = new Object();
private int sharedVariable = 0;
public void updateSharedVariable() {
synchronized (lock) {
sharedVariable++;
}
}
}
Lock接口
Lock接口提供了比synchronized更灵活的同步控制。它的实现类如ReentrantLock(可重入锁)。
可重入性
ReentrantLock允许同一个线程多次获取锁,避免死锁。例如:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {
private Lock lock = new ReentrantLock();
public void outerMethod() {
lock.lock();
try {
System.out.println("Outer method locked");
innerMethod();
} finally {
lock.unlock();
}
}
public void innerMethod() {
lock.lock();
try {
System.out.println("Inner method locked");
} finally {
lock.unlock();
}
}
}
公平性
ReentrantLock可以选择公平锁模式,按照线程请求锁的顺序分配锁。
CountDownLatch同步工具
CountDownLatch允许一个或多个线程等待其他线程完成一组操作。
基本使用
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int numThreads = 5;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
new Thread(() -> {
try {
// 模拟线程执行任务
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + " finished");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}).start();
}
latch.await();
System.out.println("All threads finished, main thread continues");
}
}
在上述代码中,主线程调用latch.await()方法等待,直到所有子线程通过latch.countDown()将计数器减为0,主线程才继续执行。
synchronized关键字提供了简单易用的同步方式,Lock接口则带来了更强大和灵活的控制,而CountDownLatch等同步工具为解决特定的多线程同步场景提供了有效的手段。合理运用这些同步机制,能够编写出高效且线程安全的程序。
本文链接:https://blog.runxinyun.com/post/548.html 转载需授权!
留言0