所以我写了这个程序来运行这个机器人类的多个线程,使用 cyclicbarrier 来同步线程。由于我对循环障碍知之甚少,我认为它会自动同步我的线程,但似乎不是。我需要做什么才能让我的机器人线程根据我的进度整数值进行同步?
public class Robot implements Runnable{
public static final int on = 0x0001;
public static final int clockwise = 0x0002;
public static final int counter = 0x0004;
int opcode;
int moveCount = 0;
int rotation, increment, progress = 0;
boolean CW;
ProgressBar prgBar;
CyclicBarrier cyclicBarrier;
Controller c;
Motor m;
public Robot(CyclicBarrier cyclicBarrier, Motor m)
{
opcode = 0;
this.cyclicBarrier = cyclicBarrier;
this.m = m;
}
public void run(){
System.out.println("Running: ");
try {
while(progress <= 24){
i = m.Engage(this, i, increment/4);
prgBar.setProgress(this, progress);
}
System.out.println("Sleeping: ");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName()+ " waiting at barrier 1");
cyclicBarrier.await();
while(progress <= 49){
i = m.Engage(this, i, increment/2);
prgBar.setProgress(this, progress);
}
System.out.println("Sleeping: ");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName()+ " waiting at barrier 2");
cyclicBarrier.await();
while(progress <= 74){
i = m.Engage(this, i, ((increment/4)*3));
prgBar.setProgress(this, progress);
}
System.out.println("Sleeping: ");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName()+ " waiting at barrier 3");
cyclicBarrier.await();
while(progress <= 99){
i = m.Engage(this, i, increment);
prgBar.setProgress(this, progress);
}
System.out.println("Sleeping: ");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName()+ " waiting at barrier 4");
cyclicBarrier.await();
} catch (Exception e){
e.printStackTrace();
}
prgBar.setProgress(this, progress);
System.out.println("Engaging: ");
}
公共类控制器{
public static void main(String[] args){
CyclicBarrier cyclicBarrier = new CyclicBarrier(4);
Motor m = new Motor();
Robot xRob = new Robot(cyclicBarrier, m);
Robot yRob = new Robot(cyclicBarrier, m);
Robot zRob = new Robot(cyclicBarrier, m);
Thread xRobThread = new Thread(xRob);
Thread yRobThread = new Thread(yRob);
Thread zRobThread = new Thread(zRob);
boolean clockwise = true, counterClockwise = false;
m.setMotor(clockwise, 14400, xRob);
m.setMotor(clockwise, 7200, yRob);
m.setMotor(counterClockwise, 28800, zRob);
xRobThread.start();
yRobThread.start();
zRobThread.start();
try {
xRobThread.join();
yRobThread.join();
zRobThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("x = %d y = %d z = %d\n\n", xRob.moveCount, yRob.moveCount, zRob.moveCount);
}
}