我试图了解更多关于在协调方法场景中使用 join() 和 CyclicBarrier - 发送和接收。基本代码来自以前的海报,我对其进行了修改以运行某些循环帐户(例如 10 次)。代码如下:
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.BrokenBarrierException;
public class Test {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(2);
Receiver receiver = new Receiver(barrier);
Sender sender = new Sender(barrier);
Thread r = new Thread(receiver);
Thread s = new Thread(sender);
r.start();
s.start();
try {
r.join();
s.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("It is over....");
}
}
class Sender implements Runnable {
private CyclicBarrier barrier;
static boolean stop = false;
private static int i = 1;
public static int limit = 10 ;
public Sender(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
while ( !stop ) {
try {
// Wait for notify.
Thread.sleep(1);
// Now do SEND.
int j = getI();
System.out.println(j);
System.out.println("SEND -" + j );
barrier.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static int getI() {
return i;
}
public static void setI(int i) {
Sender.i = i;
}
}
class Receiver implements Runnable {
private CyclicBarrier barrier;
public Receiver(CyclicBarrier barrier) {
this.barrier = barrier;
}
@Override
public void run() {
while ( Sender.getI() <= Sender.limit ) {
// Then notify.
try {
barrier.await();
int k = Sender.getI();
// Wait for ACK (the sleep just simulates that).
System.out.println("ACK -" + k );
Sender.setI(++k);
if ( Sender.getI() > Sender.limit ) {
System.out.println(k);
Sender.stop = true;
// barrier.reset();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
但是,我遇到了一个我无法解决的结果,并且与 await() 的逻辑几乎没有混淆。虽然结果似乎符合我的预期,即 SEND 和 ACK 交替 10 次。它实际上在 SEND 上运行了额外的时间,显然在第 10 次 -ACK 运行时将状态 Sender.stop 更改为 true 状态并没有“停止”Send-run() 中的 while 循环。此外,线程在 10 次(或 11 次)之后没有结束,因此我从未进入 main() 中打印出的“It is over..”。似乎该进程挂在某个地方。