Java并发编程:CountdownLatch使用

CountDownLatch是一个同步工具类,用于协调多个线程间的协作,例如在所有线程完成特定任务后再继续执行后续操作。它可以看作是join方法的扩展,支持线程池和并发任务的编排。文中通过实例展示了CountDownLatch在模拟游戏加载和RPC调用场景中的应用。

翻译过来是倒计时锁,又叫倒计时门闩,会让一个线程等待其他线程完成倒计时后才会恢复运行,是 join 功能的一个扩展

class Test1111{
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);
        new Thread(() -> {
            log.debug("begin...");
            sleep(1);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        }).start();
        new Thread(() -> {
            log.debug("begin...");
            sleep(2);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        }).start();
        new Thread(() -> {
            log.debug("begin...");
            sleep(1.5);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        }).start();
        log.debug("waiting...");
        latch.await();
        log.debug("wait end...");
    }
}

改进

相比于 join 方法,CountdownLatch 可以配合线程池使用,无需等待线程结束,这就是 CountdownLatch 的高级之处

public class TestCountDownLatch {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        test5();
    }

    private static void test5() {
        CountDownLatch latch = new CountDownLatch(3);
        ExecutorService service = Executors.newFixedThreadPool(4); // 固定线程数线程池
        service.submit(() -> {
            log.debug("begin...");
            sleep(1); // 模拟线程执行任务时间
            latch.countDown(); // 倒计时计数减 1
            log.debug("end...{}", latch.getCount()); // 拿到剩余 latch
        });
        service.submit(() -> {
            log.debug("begin...");
            sleep(1.5);
            latch.countDown(); // 倒计时计数减 1
            log.debug("end...{}", latch.getCount());
        });
        service.submit(() -> {
            log.debug("begin...");
            sleep(2);
            latch.countDown(); // 倒计时计数减 1
            log.debug("end...{}", latch.getCount());
        });
        service.submit(()->{ // 等待 3 个线程干完了做汇总操作
            try {
                log.debug("waiting...");
                latch.await(); // latch 在减为 0 之前,会一直在这阻塞
                log.debug("wait end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}

输出

17:12:08.379 c.TestCountDownLatch [pool-1-thread-3] - begin...
17:12:08.382 c.TestCountDownLatch [pool-1-thread-4] - waiting...
17:12:08.381 c.TestCountDownLatch [pool-1-thread-2] - begin...
17:12:08.379 c.TestCountDownLatch [pool-1-thread-1] - begin...
17:12:09.397 c.TestCountDownLatch [pool-1-thread-1] - end...2
17:12:09.900 c.TestCountDownLatch [pool-1-thread-2] - end...1
17:12:10.402 c.TestCountDownLatch [pool-1-thread-4] - wait end...
17:12:10.403 c.TestCountDownLatch [pool-1-thread-3] - end...0

CountdownLatch 应用

模拟一下 5 V 5 游戏等待玩家加载完成,游戏正式开始的场景

    private static void test2() throws InterruptedException {
        AtomicInteger num = new AtomicInteger(0);
        ExecutorService service = Executors.newFixedThreadPool(10, (r) -> {
            return new Thread(r, "t" + num.getAndIncrement());
        });
        CountDownLatch latch = new CountDownLatch(10);
        String[] all = new String[10];
        Random r = new Random();
        for (int j = 0; j < 10; j++) { // 模拟 10 个玩家加载游戏
            int x = j; // lambda 表达式只能引用局部的常量,变量不行,lambda 表达式实际上是内部类,默认是 final 修饰,不加修饰符也是 final 修饰
            service.submit(() -> {
                for (int i = 0; i <= 100; i++) {
                    try {
                        Thread.sleep(r.nextInt(600)); // 模拟玩家网络延时
                    } catch (InterruptedException e) {
                    }
                    all[x] = Thread.currentThread().getName() + "(" + (i + "%") + ")";
                    System.out.print("\r" + Arrays.toString(all)); // \r 后一次打印结果会覆盖掉前一次打印结果
                }
                latch.countDown(); // 一个玩家加载完成后,计数减 1
            });
        }
        latch.await(); // 等待玩家加载游戏
        System.out.println("\n游戏开始...");
        service.shutdown();
    }

CountdownLatch 应用2

现在有 3 个服务分别部署在 3 台服务器上,现在使用远程 RPC 调用获取商品,订单和物流信息

// 控制层
@RestController
public class TestCountDownlatchController {
    /*
    模拟 3 个微服务异步编排
    代码先不用理解,后面 Spring 会讲到,先熟悉就行
     */

    /**
     * 订单信息
     * @param id
     * @return
     */
    @GetMapping("/order/{id}")
    public Map<String, Object> order(@PathVariable int id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("total", "2300.00");
        sleep(2000);
        return map;
    }

    /**
     * 商品信息
     * @param id
     * @return
     */
    @GetMapping("/product/{id}")
    public Map<String, Object> product(@PathVariable int id) {
        HashMap<String, Object> map = new HashMap<>();
        if (id == 1) {
            map.put("name", "小爱音箱");
            map.put("price", 300);
        } else if (id == 2) {
            map.put("name", "小米手机");
            map.put("price", 2000);
        }
        map.put("id", id);
        sleep(1000);
        return map;
    }

    /**
     * 物流信息
     * @param id
     * @return
     */
    @GetMapping("/logistics/{id}")
    public Map<String, Object> logistics(@PathVariable int id) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("name", "中通快递");
        sleep(2500);
        return map;
    }

    private void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
// 线程池 + Future 方式
    private static void test3() throws InterruptedException, ExecutionException {
        RestTemplate restTemplate = new RestTemplate();
        log.debug("begin");
        ExecutorService service = Executors.newCachedThreadPool(); // 缓存线程池,全员救急线程
        CountDownLatch latch = new CountDownLatch(4);
        Future<Map<String,Object>> f1 = service.submit(() -> {
            Map<String, Object> response = restTemplate.getForObject("http://localhost:8080/order/{1}", Map.class, 1);
            return response;
        });
        Future<Map<String, Object>> f2 = service.submit(() -> {
            Map<String, Object> response1 = restTemplate.getForObject("http://localhost:8080/product/{1}", Map.class, 1);
            return response1;
        });
        Future<Map<String, Object>> f3 = service.submit(() -> {
            Map<String, Object> response1 = restTemplate.getForObject("http://localhost:8080/product/{1}", Map.class, 2);
            return response1;
        });
        Future<Map<String, Object>> f4 = service.submit(() -> {
            Map<String, Object> response3 = restTemplate.getForObject("http://localhost:8080/logistics/{1}", Map.class, 1);
            return response3;
        });

        System.out.println(f1.get());
        System.out.println(f2.get());
        System.out.println(f3.get());
        System.out.println(f4.get()); // get 方法会等待结果返回再往下运行
        log.debug("执行完毕");
        service.shutdown();
    }

输出结果略

C# 中实现端口转发可以使用 TcpListener 和 TcpClient 类,而断点传输文件可以使用 FileStream 和 BinaryReader/BinaryWriter 类。 以下是一个简单的示例代码,演示了如何在本地端口监听并转发传入的连接: ```csharp using System; using System.IO; using System.Net; using System.Net.Sockets; class PortForwarder { static void Main(string[] args) { int localPort = 1234; // 本地监听端口 string remoteHost = "example.com"; // 转发目标主机 int remotePort = 5678; // 转发目标端口 TcpListener listener = new TcpListener(IPAddress.Any, localPort); listener.Start(); Console.WriteLine("Listening on port " + localPort); while (true) { TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("Accepted connection from " + client.Client.RemoteEndPoint); TcpClient remoteClient = new TcpClient(remoteHost, remotePort); Console.WriteLine("Connected to remote host " + remoteHost + ":" + remotePort); // 开启一个后台线程,将两个连接之间的数据进行转发 System.Threading.Thread thread = new System.Threading.Thread(() => { try { using (var localStream = client.GetStream()) using (var remoteStream = remoteClient.GetStream()) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = localStream.Read(buffer, 0, buffer.Length)) > 0) { remoteStream.Write(buffer, 0, bytesRead); } } } catch (Exception ex) { Console.WriteLine("Error: " + ex.ToString()); } finally { client.Dispose(); remoteClient.Dispose(); } }); thread.IsBackground = true; thread.Start(); } } } ``` 要实现断点传输文件,可以根据需要进行读取和写入文件的偏移量,并在 TcpClient 之间进行数据传输。以下是一个简单的示例代码: ```csharp using System; using System.IO; using System.Net; using System.Net.Sockets; class FileTransfer { static void Main(string[] args) { string localFilePath = "localfile.dat"; // 本地文件路径 string remoteHost = "example.com"; // 文件接收主机 int remotePort = 5678; // 文件接收端口 long offset = 0; // 起始偏移量 TcpClient client = new TcpClient(remoteHost, remotePort); Console.WriteLine("Connected to remote host " + remoteHost + ":" + remotePort); using (var fileStream = new FileStream(localFilePath, FileMode.Open, FileAccess.Read)) using (var reader = new BinaryReader(fileStream)) using (var writer = new BinaryWriter(client.GetStream())) { // 将文件读取指定偏移量 fileStream.Seek(offset, SeekOrigin.Begin); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0) { writer.Write(buffer, 0, bytesRead); offset += bytesRead; Console.WriteLine("Sent " + bytesRead + " bytes at offset " + offset); } } client.Dispose(); } } ``` 注意,以上代码仅为示例,实际应用中需要考虑错误处理、超时、流关闭等情况。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值