gpt4 book ai didi

java - 多个线程作用于同一个对象

转载 作者:行者123 更新时间:2023-12-01 11:27:37 25 4
gpt4 key购买 nike

我有一个 POJO BusStop,其中包含巴士站的名称以及那里有多少乘客。

public class BusStop{
private String name;
private Integer passengers;
//setters getters constructor
public void removePassengers(Integer i){
synchronized(passengers){
this.passengers = this.passengers - i; // right now I allow them to go below zero for the sake of just testing threads;
}
}

public void increasePassengers(Integer i){
synchronized(passengers){
this.passengers = this.passengers + i;
}
}
}

还有一个 BusRide 对象,其中包含源 BusStop、目的地 BusStop 以及当前该行程中有多少乘客。

public class BusRide implements Runnable{

private BusStop source;
private BusStop destination
private Integer passengers;

public BusRide(BusStop src, BusStop dest){
this.source = src;
this.destination = dest;
}
//setters getters

@Override
public void run(){
setPassengers(15);
this.source.removePassengers(15);
setPassengers(0);
this.destination.increasePassengers(15);
}
}

主类:

public class Main{

public static void main(String[] args){
BusStop a = new BusStop("Bus-stop 1", 50);
BusStop b = new BusStop("Bus-stop 2", 45);
BusStop c = new BusStop("Bus-stop 3", 62);

Thread t1 = new Thread(new BusRide(a,b));
Thread t2 = new Thread(new BusRide(a,c));
}

}

在我的主类中,我想创建 2 个 BusRide 线程,它们将随机数量的乘客从源 BusStop 带到目的地 BusStop。但我希望 BusRide 线程从我提供给它们的对象中获取乘客,但它们有自己的 BusStop 对象实例。那么如何让两个线程在我给它们的同一个 BusStop 对象上运行呢?

最佳答案

public void removePassengers(Integer i){
synchronized(passengers){
this.passengers = this.passengers - i; // right now I allow them to go below zero for the sake of just testing threads;
}
}

public void increasePassengers(Integer i){
synchronized(passengers){
this.passengers = this.passengers + i;
}
}

以上说法是错误的。应该是

public synchronized void removePassengers(Integer i){
this.passengers = this.passengers - i; // right now I allow them to go below zero for the sake of just testing threads;
}

public synchronized void increasePassengers(Integer i){
this.passengers = this.passengers + i;
}

确实,您正在同步乘客,但将乘客分配给同步块(synchronized block)内的另一个值,本质上使两个线程可以同时调用这些方法。如果您将变量用作锁,请始终将其设置为final

关于java - 多个线程作用于同一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30692945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com