深入理解Java的并发控制工具:Locks、Conditionals与Semaphore的应用示例
在Java中,我们有三种主要的并发控制工具:Locks(锁)、Conditionals(条件变量)和Semaphore(信号量)。下面我将给出它们各自的应用示例。
- Locks(锁)
应用示例:
// 使用ReentrantLock创建一个可重入的锁
import java.util.concurrent.locks.ReentrantLock;
public class UnlockExample {
private ReentrantLock lock = new ReentrantLock();
public void methodThatUsesLock() {
lock.lock(); // 获取锁
try {
// 执行任务代码
System.out.println("Doing something critical...");
} finally {
// 无论是否发生异常,都要释放锁
lock.unlock();
}
}
public static void main(String[] args) {
UnlockExample unlockExample = new UnlockExample();
Thread thread1 = new Thread(() -> unlockExample.methodThatUsesLock()));
Thread thread2 = new Thread(() -> unlockExample.methodThatUsesLock()));
thread1.start(); // 启动第一个线程
thread2.start(); // 启动第二个线程
// 等待两个线程执行完毕
thread1.join();
thread2.join();
System.out.println("Both threads completed execution.");
}
}
在这个例子中,我们创建了一个使用ReentrantLock的类。在方法中,我们首先获取锁,然后执行任务代码,最后无论是否发生异常,都要释放锁。
- Conditionals(条件变量)
应用示例:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ConditionalExample {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void methodWithConditional() {
lock.lock(); // 获取锁
try {
// 设置条件
condition.signalAll();
// 任务代码
System.out.println("Doing something conditional...");
} finally {
// 无论是否发生异常,都要释放锁
lock.unlock();
}
}
public static void main(String[] args) {
ConditionalExample conditionalExample = new ConditionalExample();
Thread thread1 = new Thread(() -> conditionalExample.methodWithConditional()));
Thread thread2 = new Thread(() -> conditionalExample.methodWithConditional()));
thread1.start(); // 启动第一个线程
thread2.start(); // 启动第二个线程
// 等待两个线程执行完毕
thread1.join();
thread2.join();
System.out.println("Both threads completed execution.");
}
}
在这个例子中,我们创建了一个具有Condition的类。在方法中,我们首先获取锁,然后设置条件,触发所有等待的线程,最后无论是否发生异常,都要释放锁。
- Semaphore(信号量)
应用示例:
import java.util.concurrent.locks.Semaphore;
public class SemaphoreExample {
private Semaphore semaphore = new Semaphore(2); // 创建一个允许最多两个线程通过的信号量
public void methodWithSemaphore() throws InterruptedException {
semaphore.acquire(); // 获取信号量,如果信号量值为0,则会阻塞当前线程直到其他线程释放了该信号量
try {
// 任务代码
System.out.println("Doing something with Semaphore...");
} finally {
// 无论是否发生异常,都要尝试释放信号量
semaphore.release();
}
}
public static void main(String[] args) {
SemaphoreExample semaphoreExample = new SemaphoreExample();
Thread thread1 = new Thread(() -> semaphoreExample.methodWithSemaphore()));
Thread thread2 = new Thread(() -> semaphoreExample.methodWithSemaphore()));
thread1.start(); // 启动第一个线程
thread2.start(); // 启动第二个线程
// 等待两个线程执行完毕
thread1.join();
thread2.join();
System.out.println("Both threads completed execution.");
}
}
在这个例子中,我们创建了一个带有Semaphore的类。在方法中,我们首先获取信号量,如果信号量值为0,则会阻塞当前线程直到其他线程释放了该信号量,然后执行任务代码,最后无论是否发生异常,都要尝试释放信号量。
还没有评论,来说两句吧...