所以我一直在试图编写一个java程序,涉及线程。这基本上是一个线程询问共享内存资源(下面的代码中的单元类)是否允许移动的问题。我将向您展示线程中的代码示例。从cell类中提到的三种方法是同步方法,但是它们不实现等待或通知。线程管理
public void run() {
try{
while(true){
Random r = new Random();
Thread.sleep(r.nextInt(1000));
//asks the class cell permission to move if the cell is free.
if(cell.asksAccess(xi, yi, xf, yf)){
cell.releaseCell(xi, yi); //release the previous cell
move(); // move the object
cell.blockCell(xi, yi); // blocks the cell where the object is now staying.
setChanged();
notifyObservers();
}
}
} catch (InterruptedException e) {
}
}
private void move() {
int dx = xf - xi;
int dy = yf - yi;
xi += (int) Math.signum(dx);
yi += (int) Math.signum(dy);
}
就像我之前说过的,调用的所有单元类方法都是同步的。我的问题是,这不符合我的预期,当我做了一个sysout调试时,它显示线程并不总是前进,有时甚至会回到他们开始时的位置,我不明白为什么因为移动方法总是告诉他们前进并永不回头。这是与单元类同步的问题吗?或者它是移动方法?任何帮助将不胜感激。
我怀疑你是不是同步数据,以便所有线程都在读/写单元的本地varions或者其他的东西。很难告诉所示的代码。 – Gray
您应该将'Random'移到while外面,并在Thread.sleep(...);'周围移动InterruptedException。哦,并且总是至少打印'InterruptedException'并重新中断该线程。 – Gray
线程被授予访问单元的权限是100%,然后在执行if块中的任何步骤之前产生控制权。你需要同步整个'外部'逻辑块。 – Perception