CountDownLatch的介绍和使用

一、类介绍

 

    java.util.concurrent类CountDownLatch

    public class CountDownLatch extends Object

    一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。给定一个数来初始化CountDownLatch,这个值即需要等待的操作数。当某个线程需要等待一组操作时,通过调用await方法进行阻塞。某个操作完成,通过调用countDown方法使计数器减一。在该计数值到达0之前,调用await()方法的线程会一直等待。之后会释放所有等待的线程,await的后续调用将立即返回。该计数值无法被重置,即只能被初始化一次。

 

二、使用场景

  • 将计数 1 初始化的 CountDownLatch 用作一个简单的开/关锁存器,或入口:在通过调用 countDown() 的线程打开入口前,所有调用 await 的线程都一直在入口处等待;

  • 用 N 初始化的 CountDownLatch 可以使一个线程在 N 个线程完成某项操作之前一直等待,或者使其在某项操作完成 N 次之前一直等待。

 

三、使用实例

    1.等待者和任务者,一群等待者线程等待一群任务者线程完成任务。使用Countdownlatch控制等待者们等待,直到所有的任务者都完成它们的任务后,等待者才能执行。

package concurrent;

import java.util.concurrent.*;
import java.util.*;
import static net.mindview.util.Print.*;

// Performs some portion of a task:
class TaskPortion implements Runnable {
	private static int counter = 0;
	private final int id = counter++;
	private static Random rand = new Random(47);
	private final CountDownLatch latch;

	TaskPortion(CountDownLatch latch) {
		this.latch = latch;
	}

	public void run() {
		try {
			doWork();
			latch.countDown();
		} catch (InterruptedException ex) {
			// Acceptable way to exit
		}
	}

	public void doWork() throws InterruptedException {
		TimeUnit.MILLISECONDS.sleep(rand.nextInt(2000));
		print(this + "completed");
	}

	public String toString() {
		return String.format("%1$-3d ", id);
	}
}

// Waits on the CountDownLatch:
class WaitingTask implements Runnable {
	private static int counter = 0;
	private final int id = counter++;
	private final CountDownLatch latch;

	WaitingTask(CountDownLatch latch) {
		this.latch = latch;
	}

	public void run() {
		try {
			latch.await();
			print("Latch barrier passed for " + this);
		} catch (InterruptedException ex) {
			print(this + " interrupted");
		}
	}

	public String toString() {
		return String.format("WaitingTask %1$-3d ", id);
	}
}

public class CountDownLatchDemo {
	static final int SIZE = 10;

	public static void main(String[] args) throws Exception {
		ExecutorService exec = Executors.newCachedThreadPool();
		// All must share a single CountDownLatch object:
		CountDownLatch latch = new CountDownLatch(SIZE);
		for (int i = 0; i < 5; i++)
			exec.execute(new WaitingTask(latch));
		
		/*创建100个任务线程,共享一个count为100的CountDownLatch,每个线程完成任务后执行countdown将count-1,直到count为0时,
		 * 即所有的线程都完成了任务,等待线程才能执行,因此,CountDownLatch可以很方便的等待一组线程完成任务*/
		for (int i = 0; i < SIZE; i++)
			exec.execute(new TaskPortion(latch));
		print("Launched all tasks");
		exec.shutdown(); // Quit when all tasks complete
	}
} /* (Execute to see output) */// :~

 

    上面的例子中创建了5个等待者线程和10个任务者线程。创建了一个初始值为10的CountdownLatch,5个等待者共享这个CountDownLatch,意思是他们共同等待一些操作,操作的个数为10.在每个操作中调用countDown()。所以10个任务者线程也共享这个CountDownLatch,每个线程完成任务后都调用了countDown,否则等待者们会一直等待。(注意:初始计数值的大小和任务者线程数要相同)

 

输出:

Launched all tasks
7   completed
8   completed
5   completed
9   completed
0   completed
3   completed
6   completed
4   completed
1   completed
2   completed
Latch barrier passed for WaitingTask 0   
Latch barrier passed for WaitingTask 2   
Latch barrier passed for WaitingTask 4   
Latch barrier passed for WaitingTask 1   
Latch barrier passed for WaitingTask 3

 

    2.跑步比赛,所有的Player都必须等待听到枪响声后才能起跑。

package concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


class Player implements Runnable{

	private CountDownLatch latch ;
	
	
	public Player(CountDownLatch l) {
		// TODO Auto-generated constructor stub
		this.latch = l;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + " start to run!");
	}
	
}

class Guner implements Runnable{
	private CountDownLatch latch ;

	public Guner(CountDownLatch latch) {
		super();
		this.latch = latch;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i = 0;i < 3;i++){
			System.out.println(3-i);
		}
		System.out.println("Bong!");
		latch.countDown();
	}
	
	
}
public class CountDownLatchTest2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CountDownLatch latch = new CountDownLatch(1);
		ExecutorService exec = Executors.newCachedThreadPool();
		for(int i = 0;i < 8;i++){
			exec.execute(new Player(latch));
		}
		exec.execute(new Guner(latch));
	}

}

 

输出:

3
2
1
Bong!
pool-1-thread-1 start to run!
pool-1-thread-3 start to run!
pool-1-thread-8 start to run!
pool-1-thread-2 start to run!
pool-1-thread-4 start to run!
pool-1-thread-5 start to run!
pool-1-thread-6 start to run!
pool-1-thread-7 start to run!

 

三、重要方法

await
public void await()
           throws InterruptedException
使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断。
如果当前计数为零,则此方法立即返回。
如果当前计数大于零,则出于线程调度目的,将禁用当前线程,且在发生以下两种情况之一前,该线程将一直处于休眠状态:
由于调用 countDown() 方法,计数到达零;或者
其他某个线程中断当前线程。
如果当前线程:
在进入此方法时已经设置了该线程的中断状态;或者
在等待时被中断,
则抛出 InterruptedException,并且清除当前线程的已中断状态。

抛出:
InterruptedException - 如果当前线程在等待时被中断
​await
public boolean await(long timeout,                     TimeUnit unit)
              throws InterruptedException
使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断或超出了指定的等待时间。
如果当前计数为零,则此方法立刻返回 true 值。
如果当前计数大于零,则出于线程调度目的,将禁用当前线程,且在发生以下三种情况之一前,该线程将一直处于休眠状态:
由于调用 countDown() 方法,计数到达零;或者
其他某个线程中断当前线程;或者
已超出指定的等待时间。
如果计数到达零,则该方法返回 true 值。
如果当前线程:
在进入此方法时已经设置了该线程的中断状态;或者
在等待时被中断,
则抛出 InterruptedException,并且清除当前线程的已中断状态。
如果超出了指定的等待时间,则返回值为 false。如果该时间小于等于零,则此方法根本不会等待。

参数:
timeout - 要等待的最长时间
unit - timeout 参数的时间单位。
返回:
如果计数到达零,则返回 true;如果在计数到达零之前超过了等待时间,则返回 false
抛出:
InterruptedException - 如果当前线程在等待时被中断
countDown
public void countDown()
递减锁存器的计数,如果计数到达零,则释放所有等待的线程。
如果当前计数大于零,则将计数减少。如果新的计数为零,出于线程调度目的,将重新启用所有的等待线程。
如果当前计数等于零,则不发生任何操作。  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
目标检测(Object Detection)是计算机视觉领域的一个核心问题,其主要任务是找出图像中所有感兴趣的目标(物体),并确定它们的类别和位置。以下是对目标检测的详细阐述: 一、基本概念 目标检测的任务是解决“在哪里?是什么?”的问题,即定位出图像中目标的位置并识别出目标的类别。由于各类物体具有不同的外观、形状和姿态,加上成像时光照、遮挡等因素的干扰,目标检测一直是计算机视觉领域最具挑战性的任务之一。 二、核心问题 目标检测涉及以下几个核心问题: 分类问题:判断图像中的目标属于哪个类别。 定位问题:确定目标在图像中的具体位置。 大小问题:目标可能具有不同的大小。 形状问题:目标可能具有不同的形状。 三、算法分类 基于深度学习的目标检测算法主要分为两大类: Two-stage算法:先进行区域生成(Region Proposal),生成有可能包含待检物体的预选框(Region Proposal),再通过卷积神经网络进行样本分类。常见的Two-stage算法包括R-CNN、Fast R-CNN、Faster R-CNN等。 One-stage算法:不用生成区域提议,直接在网络中提取特征来预测物体分类和位置。常见的One-stage算法包括YOLO系列(YOLOv1、YOLOv2、YOLOv3、YOLOv4、YOLOv5等)、SSD和RetinaNet等。 四、算法原理 以YOLO系列为例,YOLO将目标检测视为回归问题,将输入图像一次性划分为多个区域,直接在输出层预测边界框和类别概率。YOLO采用卷积网络来提取特征,使用全连接层来得到预测值。其网络结构通常包含多个卷积层和全连接层,通过卷积层提取图像特征,通过全连接层输出预测结果。 五、应用领域 目标检测技术已经广泛应用于各个领域,为人们的生活带来了极大的便利。以下是一些主要的应用领域: 安全监控:在商场、银行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值