Java多线程同步工具:Semaphore与CountDownLatch实践示例
Semaphore和CountDownLatch是Java中常用的多线程同步工具。它们主要用来控制同时访问资源的线程数量。
- Semaphore(信号量)
Semaphore是一种二值信号机制,它维护一个当前值。当一个工作者试图获取信号量时,如果当前值大于0,那么就减少1,工作者获得信号;否则工作者等待,直到信号量释放。
示例代码:
import java.util.concurrent.Semaphore;
public class SemaphoreExample {
private Semaphore semaphore = new Semaphore(2); // 初始化信号量为2
public void workerThread() throws InterruptedException {
try {
semaphore.acquire(); // 获取信号
System.out.println("Worker " + (threadId++) + " is running ...");
// 工作逻辑
Thread.sleep(3000);
System.out.println("Worker " + (threadId++) + " finished its task ...");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(); // 释放信号量
}
}
public static void main(String[] args) throws InterruptedException {
SemaphoreExample example = new SemaphoreExample();
for (int i = 0; i < 4; i++) { // 创建4个线程实例
Thread workerThread = new Thread(example::workerThread, "Worker " + (i+1))));
workerThread.start(); // 启动线程
}
}
}
- CountDownLatch(计数器)
CountDownLatch是一个特殊的共享变量,它可以被初始化为一个给定的值。当一个工作者需要等待其他工作者完成特定操作后才能开始执行时,可以使用CountDownLatch。
示例代码:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
private CountDownLatch countDownLatch = new CountDownLatch(2); // 初始化计数器为2
public void workerThread() throws InterruptedException {
try {
countDownLatch.await(); // 等待计数器减少到0
System.out.println("Worker " + (threadId++) + " is running ...");
// 工作逻辑
Thread.sleep(3000);
System.out.println("Worker " + (threadId++) + " finished its task ...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
CountDownLatchExample example = new CountDownLatchExample();
for (int i = 0; i < 4; i++) { // 创建4个线程实例
Thread workerThread = new Thread(example::workerThread, "Worker " + (i+1))));
workerThread.start(); // 启动线程
}
countDownLatch.countDown(); // 计数器减少到0,表示所有工作已完成
}
}
总结:Semaphore和CountDownLatch都是Java中常用的多线程同步工具。Semaphore用于控制同时访问资源的线程数量,而CountDownLatch则是一个计数器,当一个工作者等待其他工作者完成特定操作后,可以使用CountDownLatch来减少计数,表示工作已完成。
还没有评论,来说两句吧...