我有一个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;
}


确实,您正在对一个乘客进行同步,但是将乘客分配给同步块内的另一个值,从本质上来说,两个线程可以同时调用方法。如果将其用作锁,请始终创建变量final

10-04 23:23