简体   繁体   English

Java CyclicBarrier

[英]Java CyclicBarrier

I have multiple threads that send the same packet and want all of them to finish before continuing to send the next packet. 我有多个线程发送相同的数据包,并希望它们全部完成后再继续发送下一个数据包。

I tested out CyclicBarrier with the following code: Test Code (was too long/messy to embed) This worked as expected printing a combination of 0 - 4 then done in a loop 我用以下代码测试了CyclicBarrier: 测试代码(太长/混乱,无法嵌入)这按预期方式工作,打印0-4的组合,然后在循环中完成

For the packet sender, the code is equivalent except the for loop is: 对于数据包发送者,该代码是等效的,除了for循环是:

for(RSocket sendSocket : sendSocketList){
    new Thread(new Send(sendSocket , toServer)).start();
}
barrier.await();

And Send is: 发送是:

private class Send implements Runnable{
    private RSocket sendSocket;
    private MPacket packet;
    public Send(RSocket sendSocket, MPacket packet){
        this.sendSocket = sendSocket;
        this.packet = packet;
    }
    public void run(){
        sendSocket.send(packet);
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

RSocket.send(packet); RSocket.send(packet); functions the same way as a regular socket's writeObject() function, except it blocks until completion (when it receives an ACK). 函数的功能与常规套接字的writeObject()函数相同,除了它会阻塞直到完成(接收到ACK时)。 Assuming the networking aspects are correct, am I using CyclicBarrier correctly? 假设网络连接正确,我是否正确使用了CyclicBarrier?

PS I should point out if I use a for loop without starting new threads it works as intended ie: PS我应该指出,如果我使用for循环而没有启动新线程,它会按预期工作,即:

for(RSocket sendSocket : sendSocketList){
    sendSocket.send(toServer);
}

Yes, the usage of CyclicBarrier is correct in this example. 是的,在此示例中, CyclicBarrier的用法是正确的。

Just be aware of one point: 请注意以下几点:

  1. According to code the barrier must be initialized to sendSocketList.size()+1 as there is also the main thread invoking await() : barrier = new CyclicBarrier(sendSocketList.size()+1); 根据代码,必须将屏障初始化为sendSocketList.size()+1因为还有主线程正在调用await()barrier = new CyclicBarrier(sendSocketList.size()+1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM