我只学过
该程序有多个线程,每个线程单独打印一组消息,但我不能在特定线程运行时阻塞其他线程。
我找到了很多方法,但我完全不理解。我的代码如下。 LeftRightCar.java:
我正在使用
+一些特定的信息以便理解
wait()
和notify()
或notifyAll()
,所以我必须使用这些函数来控制程序。该程序有多个线程,每个线程单独打印一组消息,但我不能在特定线程运行时阻塞其他线程。
我找到了很多方法,但我完全不理解。我的代码如下。 LeftRightCar.java:
public synchronized void run(){
try{
while(lock) wait();
lock=true;
System.out.println("LeftSideCar: "+left);
state="Left";
Direction();
System.out.println("RightSideCar: "+right);
state="Right";
Direction();
notifyAll();
lock=false;
}catch(InterruptedException e){
e.printStackTrace();
}
}
FrontCar.java:
public synchronized void run(){
try{
while(lock) wait();
lock=true;
System.out.println("frontCarVelocity: "+frontCarSpeed+": km/h");
Direction();
notifyAll();
lock=false;
}catch(InterruptedException e){
e.printStackTrace();
}
}
我正在使用
lock
布尔变量来使其他线程在特定线程执行期间等待。
我真的希望得到正常的结果,即不混杂消息。
但我的结果是这样的。
我如何只使用左侧汽车:接近...
前车速度:40: 公里/小时 方向:不要踩左侧车道...
方向: 右侧汽车:接近... 降低速度... 方向
: 不要踩右侧车道... 80 → 70 → 60 → 50 → 40
wait()
、notify()
或notifyAll()
来解决问题?上述两个类是Sensor.java
的子类,该类具有lock
布尔变量。+一些特定的信息以便理解
public class AutonomousCar {
public static void main(String[] args){
FrontCar f=new FrontCar();
LeftRightCar lr=new LeftRightCar();
Thread Car[]={new Thread(f),new Thread(lr)};
Car[0].start();
Car[1].start();
}
AutonomousCar
类表示具有可变传感器的汽车。 FrontCar
类是感应前车速度的传感器,LeftRightCar
类是感应左右车辆移动的传感器。
由于它是实时系统,因此可以通过Java中的线程表示并发执行。
此外,Direction
函数是一个重载函数,如下所示。
LeftRightCar.java的方向
public void Direction(){
System.out.print("Direction : ");
if(state.equals("Left")){
if(left.equals("None")) System.out.println(message.get("None"));
else if(left.equals("Approaching...")) System.out.println(message.get("Approaching-L"));
else if(left.equals("Too close...")){
System.out.println(message.get("Close-L"));
isLeftClose=true;
}
}
else if(state.equals("Right")){
if(right.equals("None")) System.out.println(message.get("None"));
else if(right.equals("Approaching...")) System.out.println(message.get("Approaching-R"));
else if(right.equals("Too close...")){
if(!isLeftClose) System.out.println(message.get("Close-R"));
else System.out.println(message.get("Close-LR"));
}
}
}
FrontCar.java的方向
public void Direction(){
System.out.print("Direction : ");
if(frontCarSpeed==100){
System.out.println(message.get("S"));
}
else if(speed<=frontCarSpeed){
System.out.print(message.get("I"));
while(speed<frontCarSpeed){
System.out.print(speed+" → ");
speed+=10;
}
System.out.println(speed);
}
else if(speed>frontCarSpeed){
System.out.print(message.get("D"));
while(speed>frontCarSpeed){
System.out.print(speed+" → ");
speed-=10;
}
System.out.println(speed);
}
}
Runnable
接口。 - molamolaLeftRightCar
和FrontCar
的完整代码? - xingbinsynchronized
存在一个重大误解。就目前而言,我看不到简单的方法来修复你的程序,除非重新编写大部分代码。也许你应该退后一步,重新学习一下教程,例如这个。 - Turing85