Android:如何使用CountDownLatch?
创始人
2024-10-13 16:30:19
0

在Android中使用CountDownLatch的方法是通过创建一个CountDownLatch对象,并在需要等待的地方调用await()方法来等待所有线程完成任务。当其他线程完成任务时,调用CountDownLatch的countDown()方法来减少计数器的值。下面是一个示例代码:

import java.util.concurrent.CountDownLatch;

public class Example {

    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(3);

        // 创建并启动三个线程
        new Thread(new Worker(latch, "Worker 1")).start();
        new Thread(new Worker(latch, "Worker 2")).start();
        new Thread(new Worker(latch, "Worker 3")).start();

        try {
            // 等待所有线程完成任务
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("All workers have finished their tasks.");
    }

    static class Worker implements Runnable {
        private final CountDownLatch latch;
        private final String name;

        public Worker(CountDownLatch latch, String name) {
            this.latch = latch;
            this.name = name;
        }

        @Override
        public void run() {
            try {
                // 模拟每个线程执行任务的时间
                Thread.sleep(1000);
                System.out.println(name + " has finished the task.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 每个线程完成任务后,调用countDown()方法减少计数器的值
                latch.countDown();
            }
        }
    }
}

在上面的示例中,我们创建了一个CountDownLatch对象,并将计数器初始值设置为3。然后,我们创建并启动了三个线程,每个线程都会执行一个模拟任务,并在完成任务后调用countDown()方法减少计数器的值。在主线程中,我们调用await()方法来等待所有线程完成任务。当所有线程都完成任务时,计数器的值将变为0,主线程将继续执行并输出"All workers have finished their tasks."。

相关内容

热门资讯

安装程序教程!aapoker脚... 安装程序教程!aapoker脚本,aapoker怎么控制牌,必胜教程(有挂神器)是一款可以让一直输的...
实测交流!聚星ai辅助工具下载... 实测交流!聚星ai辅助工具下载,wpk安卓下载辅助,科技教程(有挂透视)1、点击下载安装,微扑克wp...
必看攻略!wepoker透视a... 必看攻略!wepoker透视app下载,wpk模拟器,2025新版教程(有挂透明);玩家必备必赢加哟...
总算清楚!hhpoker到底可... 总算清楚!hhpoker到底可以作弊码,pokemmo手机脚本辅助器,2025新版教程(有挂方法);...
记者爆料!约局吧能不能开挂,w... 此外,数据分析德州(约局吧能不能开挂)辅助神器app还具备辅助透视行为开挂功能,通过对客户约局吧能不...
技术分享!wepoker辅助器... 技术分享!wepoker辅助器官方,sohoo辅助,软件教程(有挂技巧)准备好在wepoker辅助器...
信息共享!cloudpoker... 这是一款非常优秀的cloudpoker怎么开挂 ia辅助检测软件,能够让你了解到cloudpoker...
推荐十款!wepoker透视脚... 推荐十款!wepoker透视脚本视频,hhpoker买挂,安装教程(有挂神器);科技安装教程;136...
科普攻略!aapoker辅助怎... 科普攻略!aapoker辅助怎么用,hhpoker有后台操作吗,安装教程(有挂技巧)1、点击下载安装...
玩家必看教程!竞技联盟破解版最... 玩家必看教程!竞技联盟破解版最新版,云扑克有透视吗,技巧教程(有挂辅助)这是由厦门游乐互动科技有限公...