Java并发编程:CountDownLatch和Semaphore应用示例
在Java并发编程中,CountDownLatch和Semaphore都是线程同步工具,用于控制多个线程的执行顺序。这里分别给出它们的应用示例:
- CountDownLatch:
CountDownLatch是一个单向共享计数信号。当一个线程调用await方法时,该线程会阻塞直到CountDownLatch的值减少到0。
示例代码:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
private final CountDownLatch countDownLatch = new CountDownLatch(1);
public void startThread() throws InterruptedException {
countDownLatch.countDown();
System.out.println("Thread 1 started");
// 线程睡眠一段时间,以确保CountDownLatch的值减少
Thread.sleep(2000);
}
public static void main(String[] args) throws InterruptedException {
CountDownLatchExample example = new CountDownLatchExample();
Thread thread1 = new Thread(() -> example.startThread()));
Thread thread2 = new Thread(() -> example.startThread()));
// 启动两个线程
thread1.start();
thread2.start();
// 等待所有线程执行完毕
thread1.join();
thread2.join();
System.out.println("All threads have finished");
}
}
在这个示例中,CountDownLatchExample
类有一个countDownLatch
。当启动两个线程thread1
和thread2
时,它们会分别调用countDownLatch.countDown()
来减少计数器的值。
在主函数中,我们通过Thread.join()
等待所有线程执行完毕,然后输出一条消息表示所有任务已经完成。
还没有评论,来说两句吧...