Java并发编程实战:CountDownLatch与Semaphore应用实例
CountDownLatch
和Semaphore
是Java并发库中常用的两种控制共享资源的工具。以下是它们的应用实例:
CountDownLatch:
- 作用:当一个或多个线程完成他们的任务后,可以通过调用
countDown()
方法来通知其他的等待的线程。 示例:
CountDownLatch latch = new CountDownLatch(3);
// 线程1执行任务并计数
Thread t1 = new Thread(() -> {
try {
latch.countDown();
System.out.println("Task 1 done by " + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
}
}));
// 线程2和3执行任务并计数
Thread t2 = new Thread(() -> {
try {
latch.countDown();
System.out.println("Task 2 done by " + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
}
}));
Thread t3 = new Thread(() -> {
try {
latch.countDown();
System.out.println("Task 3 done by " + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
}
}));
// 启动线程
t1.start();
t2.start();
t3.start();
// 等待所有线程执行完毕,然后关闭CountDownLatch
try {
latch.await();
System.out.println("All tasks done by " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
- 作用:当一个或多个线程完成他们的任务后,可以通过调用
Semaphore:
- 作用:Semaphore是一种信号量,它用于控制同时访问共享资源的线程数量。当一个线程需要访问资源时,它可以尝试获取信号量;如果信号量已经达到了最大值(默认为1),那么当前线程将被阻塞,直到其他线程释放了信号量。
示例:
// 创建一个容量为1的Semaphore
Semaphore semaphore = new Semaphore(1);
// 线程A,需要访问资源,尝试获取信号量
Thread tA = new Thread(() -> {
try {
semaphore.acquire();
System.out.println("Thread A got resource by " + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
}
}));
// 线程B,不需要访问资源,直接释放信号量
Thread tB = new Thread(() -> {
try {
semaphore.release();
System.out.println("Thread B released resource by " + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
}
}));
// 启动线程
tA.start();
tB.start();
// 等待所有线程执行完毕,然后关闭Semaphore
try {
semaphore.awaitUninterruptibly(); // 耐心等待信号量释放
System.out.println("All tasks done by " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
以上就是CountDownLatch
和Semaphore
在Java并发编程中的基本应用实例。
还没有评论,来说两句吧...