我试图在协调的方法场景 - 发送和接收中学习更多使用带有CyclicBarrier的join()。基本代码来自之前的海报,我修改它以运行某个循环帐户(前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()中打印出来。似乎这个过程挂在了某个地方。