我已經寫出了我的代碼,指示跨過一個車道橋的北行和南行車,但是我在計數時遇到了一些麻煩。信號量和用java計算
它應該看起來像:一輛汽車在等待,然後可能是幾個,每次只有一個十字路口,並且每次都在增加。相反,它每次重複相同的三個數字。
我應該用不同的方式聲明我的計數int還是不正確地增加它?我嘗試了很多不同的方式,無法找到真正的問題。
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SingleLaneBridge {
public static void main(String[] args) {
final Bridge bridge = new Bridge();
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
Car car = new Car(bridge);
Thread th = new Thread(car);
th.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Thread th2 = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
Car car = new Car(bridge);
Thread th = new Thread(car);
th.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
th1.start();
th2.start();
}
}
class Bridge {
private final Semaphore semaphore;
public Bridge() {
semaphore = new Semaphore(1);
}
public void crossBridge(Car car) {
try {
System.out.printf("Car %s is trying to cross the bridge. \n",car.count++);
semaphore.acquire();
System.out.printf("Car %s is crossing the bridge. \n",car.count++);
Thread.sleep(5000);
} catch(InterruptedException iex) {
iex.printStackTrace();
} finally {
System.out.printf(" Car %s has crossed the bridge. \n",car.count++);
semaphore.release();
}
}
}
class Car implements Runnable {
int count = 0;
private String name;
private Bridge bridge;
public Car(Bridge bridge) {
this.bridge = bridge;
}
public void run() {
bridge.crossBridge(this);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
您正在創建一個新的'Car'對象每次,和'count'是對象的屬性。所以,每個對象都會有一個不同的'count'字段。這就是爲什麼你的計數出錯了。 –
因此,這意味着我會從汽車班級中刪除計數?或者,在我在println的運營中出現的問題更多 – guitar138