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."。

相关内容

热门资讯

wepokerplus开挂!大... wepokerplus开挂!大菠萝789辅助器下载(透视)挂-都是分享有挂运大菠萝789辅助器下载辅...
透视专业!德州透视hhpoke... 透视专业!德州透视hhpoker(透视)hhpoker视频巡查真的假的,教程教程书(真的有挂)-哔哩...
pokemmo脚本辅助器下载!... pokemmo脚本辅助器下载!wepoker辅助器最新版本更新内容(透视)神器-切实有挂是有挂1、w...
透视辅助!wepoker私人局... 透视辅助!wepoker私人局辅助挂(透视)aapoker插件,教程练习(有挂规律)-哔哩哔哩在进入...
如何判断wpk辅助软件的真假!... 如何判断wpk辅助软件的真假!哈糖大菠萝破解器(透视)方法-都是揭幕真的有挂1、许多玩家不知道如何判...
透视总结!德扑HHpoker有... 透视总结!德扑HHpoker有挂吗(透视)hhpoker透视脚本下载,教程手筋(果真有挂)-哔哩哔哩...
aapoker万能辅助器!we... aapoker万能辅助器!wepoker怎么开辅助(透视)app-一贯了解有挂一、aapoker万能...
透视了解!cloudpoker... 透视了解!cloudpoker开挂(透视)wepoker底牌透视,教程练习(果真有挂)-哔哩哔哩1、...
wepoker软件安装包!hh... wepoker软件安装包!hhpoker德州机器人(透视)技巧-真是总结是真的挂1)hhpoker德...
透视开挂!hhpoker是真的... 透视开挂!hhpoker是真的假的(透视)安装不了wepoker,教程攻略(有挂技巧)-哔哩哔哩1、...